Skip to content

Instantly share code, notes, and snippets.

@shahjugal
Last active July 18, 2022 04:15
Show Gist options
  • Save shahjugal/148c57b924bbea89ffb333d6c6fa5402 to your computer and use it in GitHub Desktop.
Save shahjugal/148c57b924bbea89ffb333d6c6fa5402 to your computer and use it in GitHub Desktop.
Bubble Sort
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