Skip to content

Instantly share code, notes, and snippets.

@Martin91
Last active December 26, 2015 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Martin91/7217062 to your computer and use it in GitHub Desktop.
Save Martin91/7217062 to your computer and use it in GitHub Desktop.
A bubble sort example based on C++ source code
#include <iostream>
using namespace std;
void bubbleSort(int array[], int length)
{
for(int i = 0; i < length - 1; i ++)
{
for(int j = length - 1; j > i; j--)
{
if(array[j-1] > array[j])
{
// Swap elements if the lower-indexed key's value is greater
// than its higher-indexed neighbor
array[j] = array[j-1] + array[j];
array[j-1] = array[j] - array[j-1];
array[j] = array[j] - array[j-1];
}
}
}
}
int main()
{
int array[] = {11, 23, 34, 24, 3, 45, 112, 44, 73, 89};
int length = sizeof(array) / sizeof(int);
bubbleSort(array, length);
for(int i = 0; i < length; i++)
{
cout<<"The "<<i + 1<<"th element is: "<<array[i]<<endl;
}
}
@Martin91
Copy link
Author

Bubble Sort consists of a simple double for loop. The first iteration of the inner loop moves through the record array from bottom to top, comparing adjacent keys. If the lower-indexed key's value is greater than its higher-indexed neighbor, then the two values are swapped. Once the smallest value is encountered, this process will cause it to "bubble" up to the top of the array. The second pass through the array repeats this process.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment