Created
June 17, 2016 04:38
-
-
Save dreampiggy/3e3909699f77fbb8b4ef9f22bebfd4e6 to your computer and use it in GitHub Desktop.
QuickSort-Objective-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
void quicksortInPlace(NSMutableArray *array, NSInteger first, NSInteger last, NSComparator comparator) { | |
if (first >= last) return; | |
id pivot = array[(first + last) / 2]; | |
NSInteger left = first; | |
NSInteger right = last; | |
while (left <= right) { | |
while (comparator(array[left], pivot) == NSOrderedAscending) | |
left++; | |
while (comparator(array[right], pivot) == NSOrderedDescending) | |
right--; | |
if (left <= right) | |
[array exchangeObjectAtIndex:left++ withObjectAtIndex:right--]; | |
} | |
quicksortInPlace(array, first, right, comparator); | |
quicksortInPlace(array, left, last, comparator); | |
} | |
NSArray* quicksort(NSArray *unsorted, NSComparator comparator) { | |
NSMutableArray *a = [NSMutableArray arrayWithArray:unsorted]; | |
quicksortInPlace(a, 0, a.count - 1, comparator); | |
return a; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment