Last active
November 1, 2015 16:12
-
-
Save sumanth232/f6cb33669dcff09e6647 to your computer and use it in GitHub Desktop.
A simple clean code for partitioning an array
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
/* Partition an array with 0s and 1s */ | |
void partition(int* v, int n) { | |
int i=0, k=n; | |
while(i<k) { | |
if(v[i] == 0) i++; | |
else swap(v[i], v[--k]); | |
} | |
} | |
/* Partition step in Quicksort algorithm */ | |
void partitionPivot (int* v, int n) { | |
// Taking the pivot as the 0th element | |
int pivot = v[0]; | |
int i=1, k=n; | |
while(i<k) { | |
if(v[i] <= pivot) i++; | |
else swap(v[i], v[--k]); | |
} | |
if(k-1 > 0) swap(v[0], v[k-1]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment