Last active
October 5, 2018 00:36
-
-
Save gregyjames/ca15e6b5e422f886768bdecd40d84087 to your computer and use it in GitHub Desktop.
Bubble Sort (C++)
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
#include <algorithm> | |
//Array to sort | |
int arr = [] | |
//Get length of array | |
const int length = sizeof(arr)/sizeof(arr[0]); | |
int count = length; | |
bool swapped = false; | |
for(int i=0; i < length; i++){ | |
for(int x = 0; x < count - 1; x++){ | |
//Swap the next element with the next one if its smaller. | |
if(arr[x+1] < arr[x]){ | |
//Actually swap the elements | |
swap(arr[x], arr[x+1]) | |
swapped = true; | |
} | |
} | |
//Lowers the count varible, since we can guarantee that the last element is sorted | |
count=count - 1; | |
//If no swaps occure, assume that the list is sorted and break to prevent additional cycles | |
if(swapped){ | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment