Last active
July 18, 2022 04:15
-
-
Save shahjugal/148c57b924bbea89ffb333d6c6fa5402 to your computer and use it in GitHub Desktop.
Bubble Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void bubbleSort(vector<int>& arr) | |
{ | |
int lastIndex = arr.size() - 1; | |
// n-1 passes | |
for(int i = 0; i < lastIndex; i++){ | |
bool swapped = false; | |
// from first element to last/secondLast/thirdLast element depending on pass count. | |
for(int j = 0; j < lastIndex - i; j++){ | |
// swap if j-th element is more than j+1-th index. | |
if(arr[j] > arr[j+1]){ | |
swap(arr[j], arr[j+1]); | |
swapped = true; | |
} | |
} | |
// if array is already sorted. | |
if(!swapped) | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment