Skip to content

Instantly share code, notes, and snippets.

@kaysush
Last active December 20, 2015 22:28
Show Gist options
  • Save kaysush/6204875 to your computer and use it in GitHub Desktop.
Save kaysush/6204875 to your computer and use it in GitHub Desktop.
This is the naive implementation of Bubble Sort. It doesn't takes into account that after N(th) iteration last N-1 elements are sorted. It uses the optimization that if array is already sorted then it breaks out of the loop.
void bubble_sort(int * array,int length) {
int i,j,temp;
comparison_count = swap_count = 0;
for ( i = 0 ; i < length ; i++) {
swapped = 0;
for ( j = 0 ; j < length - 1; j++) {
comparison_count++;
if ( array[j] > array[j+1]) {
swap_count++;
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment