-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathmain.m
More file actions
75 lines (56 loc) · 2.34 KB
/
Copy pathmain.m
File metadata and controls
75 lines (56 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//
// main.m
// QuickSort
//
// Created by Matt Eaton on 11/11/18.
// Copyright © 2018 Matt Eaton. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface QuickSort: NSObject
- (NSArray *) quickSortArray:(NSArray *)unsortedArray;
@end
@implementation QuickSort
// ---------- Start of Quick Sort -------------
- (NSArray *) quickSortArray:(NSArray *)unsortedArray {
// Time complexity: O(n^2).
// * First time arround is to separate the entire array.
// * Second time around should sort the rest of the array.
// Space complexity: O(log n) +1 for unsortedArray but the mutable copy never gets added to the autorelease pool.
// All of the arrays that are not attached to the returnArray are released by a compiler pass at the end of the method.
int count = (int)[unsortedArray count];
if (count <= 1) {
return unsortedArray;
}
int pivot = [[unsortedArray objectAtIndex: (count/2)] intValue];
NSMutableArray *smallerThanArray = [NSMutableArray array];
NSMutableArray *largerThanArray = [NSMutableArray array];
NSMutableArray *pivotArray = [NSMutableArray array];
[pivotArray addObject: @(pivot)];
for (int e = 0; e < count; e++) {
int num = [[unsortedArray objectAtIndex:e] intValue];
if (num < pivot) {
[smallerThanArray addObject: @(num)];
} else if (num > pivot) {
[largerThanArray addObject: @(num)];
// To address the possibly duplicate that is defined in the pivot, in this case 4.
} else if (e != (count/2) && pivot == num) {
[pivotArray addObject: @(num)];
}
}
NSMutableArray *returnArray = [NSMutableArray array];
[returnArray addObjectsFromArray: [self quickSortArray: smallerThanArray]];
[returnArray addObjectsFromArray: pivotArray];
[returnArray addObjectsFromArray: [self quickSortArray: largerThanArray]];
return returnArray;
}
// ---------- End of Quick Sort ---------------
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSArray *quickSortData = @[@4, @3, @10, @44, @6, @4, @1, @7];
QuickSort *qs = [[QuickSort alloc] init];
NSArray *sortedNumbers = [qs quickSortArray:quickSortData];
NSLog(@"Sorted Numbers %@", sortedNumbers);
}
return 0;
}