-
Notifications
You must be signed in to change notification settings - Fork 178
/
Copy pathday 20.swift
40 lines (32 loc) · 907 Bytes
/
day 20.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
// Bubble Sort Solution
import Foundation
// read the integer n
let n = Int(readLine()!)!
// read the array
var arr = readLine()!.components(separatedBy: " ").map{ Int($0)! }
// SOLUTION:
var numberOfSwaps = 0
public func bubbleSort<T> (_ elements: [T]) -> [T] where T: Comparable {
return bubbleSort(elements, <)
}
public func bubbleSort<T> (_ elements: [T], _ comparison: (T,T) -> Bool) -> [T] {
var array = elements
for i in 0..<array.count {
for j in 1..<array.count-i {
if comparison(array[j], array[j-1]) {
let tmp = array[j-1]
array[j-1] = array[j]
array[j] = tmp
numberOfSwaps += 1
}
}
if numberOfSwaps == 0 {
break
}
}
return array
}
var sortedArray = bubbleSort(arr)
print("Array is sorted in \(numberOfSwaps) swaps.")
print("First Element: \(sortedArray[0])")
print("Last Element: \(sortedArray[n - 1])")