10000 Merge pull request #18 from anantcodes/master · delphi1977/Swift@bdabc14 · GitHub
[go: up one dir, main page]

Skip to content

Commit bdabc14

Browse files
authored
Merge pull request TheAlgorithms#18 from anantcodes/master
Bubble sort algorithm added
2 parents 9236855 + 3b21774 commit bdabc14

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

sorts/BubbleSort.swift

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import Foundation
2+
3+
extension Array where Element: Comparable {
4+
5+
func bubbleSort(by areInIncreasingOrder: ((Element, Element) -> Bool) = (<)) -> [Element] {
6+
var data = self
7+
8+
for i in 0..<(data.count-1) {
9+
for j in 0..<(data.count-i-1) where areInIncreasingOrder(data[j+1], data[j]) {
10+
data.swapAt(j, j + 1)
11+
}
12+
}
13+
14+
return data
15+
}
16+
}
17+
18+
func swap<T: Comparable>(left: inout T, right: inout T) {
19+
print("Swapping \(left) and \(right)")
20+
let temp = right
21+
right = left
22+
left = temp
23+
}
24+
25+
// The code below can be used for testing
26+
27+
// let numberList : Array<Int> = [8, 2, 10, 9, 7, 5]
28+
// let results: Array<Int> = numberList.bubbleSort()
29+
// print(results)

0 commit comments

Comments
 (0)
0