Skip to content

Commit f344b76

Browse files
Wesley-ArringtonButt4cak3
authored andcommitted
Added BogoSort in Swift 4.1 (#161)
1 parent 571f0c9 commit f344b76

File tree

4 files changed

+47
-1
lines changed

4 files changed

+47
-1
lines changed

CONTRIBUTORS.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,6 @@ Maxime Dherbécourt
99
Jess 3Jane
1010
Pen Pal
1111
Chinmaya Mahesh
12-
Kjetil Johannessen
1312
Unlambder
13+
Kjetil Johannessen
14+
CDsigma

book.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,10 @@
8383
"lang": "go",
8484
"name": "Go"
8585
},
86+
{
87+
"lang": "swift",
88+
"name": "Swift"
89+
},
8690
{
8791
"lang": "racket",
8892
"name": "Racket"

chapters/sorting_searching/bogo/bogo_sort.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ In code, it looks something like this:
3535
[import, lang:"c_cpp"](code/c++/bogosort.cpp)
3636
{% sample lang="rs" %}
3737
[import, lang:"rust"](code/rust/bogosort.rs)
38+
{% sample lang="swift" %}
39+
[import, lang:"swift"](code/swift/bogosort.swift)
3840
{% endmethod %}
3941

4042
That's it.
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import Foundation
2+
3+
4+
func isSorted(inputArray: [Int]) -> Bool {
5+
6+
for i in 0..<inputArray.count-1 {
7+
if inputArray[i] > inputArray[i+1] {
8+
return false
9+
}
10+
}
11+
12+
return true
13+
}
14+
15+
16+
17+
func shuffle(inputArray: inout [Int]) -> [Int] {
18+
19+
var shuffledArray = [Int]()
20+
21+
for _ in 0..<inputArray.count {
22+
let rand = Int(arc4random_uniform(UInt32(inputArray.count)))
23+
shuffledArray.append(inputArray[rand])
24+
inputArray.remove(at: rand)
25+
}
26+
27+
return shuffledArray
28+
}
29+
30+
31+
32+
func bogoSort(sortArray: inout [Int]) -> [Int] {
33+
34+
while(!isSorted(inputArray: sortArray)) {
35+
sortArray = shuffle(inputArray: &sortArray)
36+
}
37+
38+
return sortArray
39+
}

0 commit comments

Comments
 (0)