Skip to content

Instantly share code, notes, and snippets.

@dreampiggy
Created June 17, 2016 04:38
Show Gist options
  • Save dreampiggy/3e3909699f77fbb8b4ef9f22bebfd4e6 to your computer and use it in GitHub Desktop.
Save dreampiggy/3e3909699f77fbb8b4ef9f22bebfd4e6 to your computer and use it in GitHub Desktop.
QuickSort-Objective-C
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