Bubble Sort
Bubble Sort
In this tutorial, you will learn about the bubble sort algorithm and its
implementation in C++.
2. If the first element is greater than the second element, they are
swapped.
3. Now, compare the second and the third elements. Swap them if they
are not in order.
4. The above process goes on until the last element.
Compare the
Adjacent Elements
2. Remaining Iteration
The same process goes on for the remaining iterations.
After each iteration, the largest element among the unsorted elements is
placed at the end.
Put the largest element at the
end
In each iteration, the comparison takes place up to the last unsorted
element.
bubbleSort(array)
for i <- 1 to indexOfLastUnsortedElement-1
if leftElement > rightElement
swap leftElement and rightElement
end bubbleSort
Bubble Sort Code in C++
C++
// Bubble sort in C++
#include <iostream>
using namespace std;
// print array
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
cout << " " << array[i];
}
cout << "\n";
}
int main() {
int data[] = {-2, 45, 0, 11, -9};
bubbleSort(data, size);
bubbleSort(array)
swapped <- false
for i <- 1 to indexOfLastUnsortedElement-1
if leftElement > rightElement
swap leftElement and rightElement
swapped <- true
end bubbleSort
Optimized Bubble Sort in C++
C++
// Optimized bubble sort in C++
#include
using namespace std;
swapped = 1;
}
}
int main() {
int data[] = {-2, 45, 0, 11, -9};
bubbleSort(data, size);
#include
using namespace std;
swapped = 1;
}
}
// print an array
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
cout << " " << array[i];
}
cout << "\n";
}
int main() {
int data[5];
cout<<”Enter 5 numbers:”<<endl;
for (int i=0; i<5; ++i)
{
cin >> data (i);
}
bubbleSort(data, size);