Last active
June 1, 2017 11:26
-
-
Save CraftedPvP/c9e320b50f041cf7cbcc96c1e5e732c7 to your computer and use it in GitHub Desktop.
Contains Insertion, Quick, and Bubble Sorting snippets for C++. Links provided for further description of what each sorting algorithm does. Hope this helps :)
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
// | |
//---Insertion Sort - Sorts the data by pairs then checks j from those behind it---// | |
//--- Link: http://cforbeginners.com/insertionsort.html ---// | |
// | |
void insertion_sort (int arr[], int length){ | |
int j, temp; | |
for (int i = 1; i < length; i++){ | |
j = i; | |
while (j > 0 && arr[j] < arr[j-1]){ | |
temp = arr[j]; | |
arr[j] = arr[j-1]; | |
arr[j-1] = temp; | |
j--; | |
} | |
} | |
} | |
// | |
//---Quick Sort - Sorts the data by pairs by getting the minimum end then swapping it with the current---// | |
//--- Link: http://www.algolist.net/Algorithms/Sorting/Quicksort ---// | |
// | |
void quick_sort(int arr[], int left, int right) { | |
int i = left, j = right; | |
int tmp; | |
int pivot = arr[(left + right) / 2]; | |
//partition | |
while (i <= j) { | |
while (arr[i] < pivot) | |
i++; | |
while (arr[j] > pivot) | |
j--; | |
if (i <= j) { | |
tmp = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = tmp; | |
i++; | |
j--; | |
} | |
}; | |
/* recursion */ | |
if (left < j) | |
quickSort(arr, left, j); | |
if (i < right) | |
quickSort(arr, i, right); | |
} | |
// | |
//--- Bubble Sort - Swap adjacent pairs. If it's not in the wrong order then swap them. ---// | |
//--- Link: http://www.thecrazyprogrammer.com/2011/11/c-program-to-sort-array-by-using-bubble.html ---// | |
// | |
int size=5, temp; | |
int container[size]; | |
for(int i=1;i<size;++i) { | |
for(int j=0;j<(size-i);++j){ | |
if(container[j]>container[j+1]){ | |
temp=container[j]; | |
container[j]=container[j+1]; | |
container[j+1]=temp; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment