Last active
October 22, 2020 14:57
-
-
Save trilliwon/8b62ab763380e00c6e56b39d765fcf09 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: [Previous](@previous) | |
/*: | |
# Bubble Sort | |
### Runtime: | |
- Best: O(N) | |
- Average: O(N^2) | |
- Worst: O(N^2) | |
### Memory: | |
- O(1) | |
```swift | |
var items = [6, 2, 7, 4, 5, 10] | |
items.bubbleSort() // in place sorting | |
let sortedItems = items.bubbleSorted() // return sorted array | |
``` | |
*/ | |
extension Array where Element : Comparable { | |
public mutating func bubbleSort() { | |
for i in 0..<count { | |
for j in 1..<(count - i) { | |
if self[j - 1] > self[j] { | |
self.swapAt(j, j - 1) | |
} | |
} | |
} | |
} | |
public func bubbleSorted() -> [Element] { | |
var elements = self | |
elements.bubbleSort() | |
return elements.sorted() | |
} | |
} | |
var items = [6, 2, 7, 4, 5, 10] | |
items.shuffle() | |
print("Array to be sorted => ", items) | |
items.bubbleSort() | |
print("Sorted in place => ", items) | |
print("----") | |
items.shuffle() | |
print("Array to be sorted => ", items) | |
let sortedItems = items.bubbleSorted() | |
print("Sorted in place => ", sortedItems) | |
//: [Next](@next) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment