Last active
December 26, 2015 21:38
-
-
Save Martin91/7217062 to your computer and use it in GitHub Desktop.
A bubble sort example based on C++ source code
This file contains hidden or 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
#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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.