Last active
July 16, 2016 03:36
-
-
Save raunaqbn/217073a0cf75ae1a968068bcb22a8ac9 to your computer and use it in GitHub Desktop.
Quick Sort
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
void swap(int& a, int& b) | |
{ | |
int temp = a; | |
a = b; | |
b = temp; | |
} | |
void partition(int * arr, int left, int right) | |
{ | |
int pivotValue = arr[right]; | |
int pos = left -1; // This is the position in the subarray where the pivot should be present | |
for (int j = left; j < right; j++) | |
{ | |
if (arr[j] < pivotValue) | |
{ | |
//This means that this element should be on the left of the pivot | |
pos++; | |
// we need to move the pivot right so we swap with this element the pivot position | |
swap (arr[pos],arr[j]); | |
} | |
} | |
//At this point the pos is pointing to the position just before the pivot | |
swap(arr[pos+1], arr[right]); | |
return (pos+1); | |
} | |
void quickSort(int* arr, int left, int right) | |
{ | |
if (left < right) | |
{ | |
int pos = partition(arr, left, right); | |
quickSort(arr,left, (pos - 1)); | |
quickSort(arr, (pos+1), right); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment