-
Notifications
You must be signed in to change notification settings - Fork 276
/
Array.swift
350 lines (208 loc) · 8.42 KB
/
Array.swift
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
//
// Array.swift
// SwiftStructures
//
// Created by Wayne Bishop on 7/1/16.
// Copyright © 2016 Arbutus Software Inc. All rights reserved.
//
import Foundation
extension Array where Element: Comparable {
//determines the longest sequence of specified values
func longestSequence(of key: Element) -> Int {
//initial values
var current: Element
var counter: Int = 0
var longest: Int = 0
//iterate through list - O(n)
for s in self {
//current iteration
current = s
if current == key {
counter += 1
}
else {
counter = 0
}
//preserve the longest sequence
if counter >= longest {
longest = counter
}
}
//return count results
return longest
}
//MARK: Index Operation
//returns middle index
func midIndex() -> Index {
return startIndex + (count / 2)
}
//MARK: - Binary Search
/*
binary search algorithm. Find the value at a specified index.
note the use array slicing to adjust the upper and lower array bounds.
returns true if the key was found in the sequence. Average performance: O(log n).
*/
mutating func binarySearch(forElement key: Element) -> Bool {
var result = false
//establish indices
let min = self.startIndex
let max = self.endIndex - 1
let mid = self.midIndex()
//check bounds
if key > self[max] || key < self[min] {
print("search value \(key) not found..")
return false
}
//evaluate chosen number..
let n = self[mid]
print(String(describing: n) + "value attempted..")
if n > key {
var slice = Array(self[min...mid - 1])
result = slice.binarySearch(forElement: key)
}
else if n < key {
var slice = Array(self[mid + 1...max])
result = slice.binarySearch(forElement: key)
}
else {
print("search value \(key) found..")
result = true
}
return result
}
//MARK: - Linear Search
/*
linear search algorithm - use fast enumeration to iterate through a sequence
of values. performance of O(n).
*/
func linearSearch(forElement key: Element) -> Bool {
//check all possible values
for number in self {
if number == key {
return true
}
}
return false
}
//MARK: - Insertion Sort
/*
insertion sort algorithm - rank set of random numbers lowest to highest by
inserting numbers based on a sorted and unsorted side. performance of O(n2).
*/
func insertionSort() -> Array<Element> {
//check for trivial case
guard self.count > 1 else {
return self
}
var output: Array<Element> = self
for primaryindex in 0..<output.count {
let key = output[primaryindex]
var secondaryindex = primaryindex
while secondaryindex > -1 {
print("comparing \(key) and \(output[secondaryindex])")
if key < output[secondaryindex] {
//move into correct position
output.remove(at: secondaryindex + 1)
output.insert(key, at: secondaryindex)
}
secondaryindex -= 1
}
}
return output
}
//MARK: - Bubble Sort
/*
bubble sort algorithm - rank items from the lowest to highest by swapping
groups of two items from left to right. The highest item in the set will bubble up to the
right side of the set after the first iteration. performance of O(n2).
*/
func bubbleSort() -> Array<Element> {
//check for trivial case
guard self.count > 1 else {
return self
}
//mutated copy
var output: Array<Element> = self
for primaryIndex in 0..<self.count {
let passes = (output.count - 1) - primaryIndex
//"half-open" range operator
for secondaryIndex in 0..<passes {
let key = output[secondaryIndex]
print("comparing \(key) and \(output[secondaryIndex + 1])")
//compare / swap positions
if (key > output[secondaryIndex + 1]) {
output.swapAt(secondaryIndex, secondaryIndex + 1)
}
}
}
return output
}
//MARK: - Selection Sort
/*
selection sort algorithm - rank items from the lowest to highest by iterating through
the array and swapping the current iteration with the lowest value in the rest of the array
until it reaches the end of the array. performance of O(n2).
*/
func selectionSort() -> Array<Element> {
//check for trivial case
guard self.count > 1 else {
return self
}
//mutated copy
var output: Array<Element> = self
for primaryindex in 0..<output.count {
var minimum = primaryindex
var secondaryindex = primaryindex + 1
while secondaryindex < output.count {
print("comparing \(output[minimum]) and \(output[secondaryindex])")
// store lowest value as minimum
if output[minimum] > output[secondaryindex] {
minimum = secondaryindex
}
secondaryindex += 1
}
// swap minimum value with array iteration
if primaryindex != minimum {
output.swapAt(primaryindex, minimum)
}
}
return output
}
//MARK: - Quick Sort
/*
quicksort algorithm - Ranks numbers through a series of swaps.
Based on "conceptually" sorting a collection subset based on a "wall" and "pivot".
Best case performance of O(n log(n)). Worst case performance of O(n2).
*/
mutating func quickSort() -> Array<Element> {
func qSort(start startIndex: Int, _ pivot: Int) {
if (startIndex < pivot) {
let iPivot = qPartition(start: startIndex, pivot)
qSort(start: startIndex, iPivot - 1)
qSort(start: iPivot + 1, pivot)
}
}
qSort(start: 0, self.endIndex - 1)
return self
}
//sorts collection-range based on pivot
mutating func qPartition(start startIndex: Int, _ pivot: Int) -> Int {
var wallIndex: Int = startIndex
//compare range with pivot
for currentIndex in wallIndex..<pivot {
print("current is: \(self[currentIndex]). pivot is \(self[pivot])")
if self[currentIndex] <= self[pivot] {
if wallIndex != currentIndex {
self.swapAt(currentIndex, wallIndex)
}
//advance wall
wallIndex += 1
}
}
//move pivot to final position
if wallIndex != pivot {
self.swapAt(wallIndex, pivot)
}
return wallIndex
}
}