-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBubbleSort.swift
32 lines (30 loc) · 1.01 KB
/
BubbleSort.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
// Bubble Sort Swift
// Solution Time complexity: O(n^2); Space Complexity: O(1)
//func bubbleSort(arrayToBeSorted: inout [Int]) {
// for i in 0 ..< arrayToBeSorted.count {
// for j in i ..< arrayToBeSorted.count {
// if arrayToBeSorted[i] > arrayToBeSorted[j] {
// let temp = arrayToBeSorted[i]
// arrayToBeSorted[i] = arrayToBeSorted[j]
// arrayToBeSorted[j] = temp
// }
// }
// }
//}
func bubbleSort(arrayToBeSorted: inout [Int]) {
for _ in arrayToBeSorted {
print(arrayToBeSorted)
var isSorted = true
for i in 0 ..< arrayToBeSorted.count - 1 {
if arrayToBeSorted[i] > arrayToBeSorted[i+1] { // change to < will make decreasing order
isSorted = false
let temp = arrayToBeSorted[i]
arrayToBeSorted[i] = arrayToBeSorted[i+1]
arrayToBeSorted[i+1] = temp
}
}
if isSorted {
return
}
}
}