What is Bubble Sort ?
Bubble sort is a sorting algorithm that works by repeatedly stepping through lists that need to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order.
Algorithm
- Loop through the whole array starting from index 1
- If the number in the array at index i-1 is greater than i, swap the numbers and continue
- Once the end of the array is reached, start looping again from the beginning
- Once no more elements can be swapped, the sorting is complete
Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse sorted.
Best Case Time Complexity: O(n). Best case occurs when array is already sorted.
Auxiliary Space: O(1)
Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted.
Sorting In Place: Yes
Stable: Yes
Implementation
Bubble sort works by going through the array multiple times and swapping elements that are out of order as we go through the array. Every pass through the array, we move the largest element to the end.
Code
// Bubble Sort #include<iostream.h> #include<conio.h> // Display For Array void display(int number[],int size){ for(int i=0;i<size;i++){ cout<<" "<<number[i]; (size==i+1)? cout<<".": cout<<","; } } void main(){ clrscr(); int size = 8; int array[10]; array[0] = 34; array[1] = 304; array[2] = 302; array[3] = 745; array[4] = 91; array[5] = 5; array[6] = 764; array[7] = 200; cout<<"\n ------Bubble Sort------ "; cout<<"\n Before Sorting \n"; display(array,size); cout<<"\n After Sorting \n"; //Bubble Sort for(int i = size - 1; i >= 0; i--){ for(int j = 1; j <= i; j++){ if(array[j-1] > array[j]){ //Swap int temp_A = array[j-1]; array[j-1] = array[j]; array[j] = temp_A; } } } display(array,size); getch(); }