Skip to content

Commit a9b6c5f

Browse files
committed
correction in the algorithm
1 parent 106b65e commit a9b6c5f

File tree

2 files changed

+10
-14
lines changed

2 files changed

+10
-14
lines changed

Bubble Sort/MyPlayground.playground/Contents.swift

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,11 @@ public func BubbleSort<T> (_ elements: [T]) -> [T] where T: Comparable {
44
var array = elements
55

66
for i in 0..<array.count {
7-
for j in i+1..<array.count {
8-
if array[j] < array[i] {
9-
let tmp = array[i]
10-
array[i] = array[j]
7+
for j in 1..<array.count-i {
8+
print(array,"comparing [\(j-1)] with [\(j)]")
9+
if array[j] < array[j-1] {
10+
let tmp = array[j-1]
11+
array[j-1] = array[j]
1112
array[j] = tmp
1213
}
1314
}
@@ -16,12 +17,7 @@ public func BubbleSort<T> (_ elements: [T]) -> [T] where T: Comparable {
1617
return array
1718
}
1819

19-
20-
var array = [Int]()
21-
22-
for _ in 0...10 {
23-
array.append(Int.random(in: 0...500))
24-
}
20+
var array = [4,2,1,3]
2521

2622
print("before:",array)
2723
print("after:",BubbleSort(array))

Bubble Sort/MyPlayground.playground/Sources/BubbleSort.swift

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,10 @@ public func BubbleSort<T> (_ elements: [T]) -> [T] where T: Comparable {
2929
var array = elements
3030

3131
for i in 0..<array.count {
32-
for j in i+1..<array.count {
33-
if array[j] < array[i] {
34-
let tmp = array[i]
35-
array[i] = array[j]
32+
for j in 1..<array.count-i {
33+
if array[j] < array[j-1] {
34+
let tmp = array[j-1]
35+
array[j-1] = array[j]
3636
array[j] = tmp
3737
}
3838
}

0 commit comments

Comments
 (0)