A sorting algorithm which splits the input array in 2 parts, the sorted part and the unsorted part. In every iteration, it finds the extremum element in the unsorted array using pairwise swapping and adds it to the sorted array.
Characteristic | Value | Notes |
---|---|---|
Average Time Complexity | O(n2) | Same for worst case |
Best Time Complexity | O(n) | For a sorted array |
Space Complexity | O(1) | No extra storage required |
bubble_sort()
function is pretty simple,
it works with 2 iterators:
itr_1
: Holds the index of the end of
sorted array after which the extremum from the sorted array
will be added after every iteration.
itr_2
: Traverses the unsorted array to find the
extremum value in every iteration using pairwise swapping.
itr_1
to the left by 1 and iterate over the unsorted array
again.
// function for bubble sort
void bubble_sort(int arr[], int n) {
// i = itr_1 , j = itr_2
for(int i = n; i >= 1; --i) {
bool swapped = false;
for(int j = 0; j < i - 1; ++j) {
if(arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
swapped = true;
}
}
if(!swapped) {
break;
}
}
return;
}