Skip to content

Commit d4fd216

Browse files
authored
Merge pull request #744 from JulioBBL/bubble-sort
Bubble sort algorithm correction and readme improvements
2 parents bdabfe0 + ab3b6cd commit d4fd216

File tree

7 files changed

+189
-1
lines changed

7 files changed

+189
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import Foundation
2+
3+
var array = [4,2,1,3]
4+
5+
print("before:",array)
6+
print("after:",BubbleSort(array))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
//
2+
// BubbleSort.swift
3+
//
4+
// Created by Julio Brazil on 1/10/18.
5+
//
6+
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
7+
// associated documentation files (the "Software"), to deal in the Software without restriction, including
8+
// without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
// copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
10+
// following conditions:
11+
//
12+
// The above copyright notice and this permission notice shall be included in all copies or substantial
13+
// portions of the Software.
14+
//
15+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
16+
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
17+
// EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
18+
// AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
19+
// OR OTHER DEALINGS IN THE SOFTWARE.
20+
//
21+
22+
import Foundation
23+
24+
/// Performs the bubble sort algorithm in the array
25+
///
26+
/// - Parameter elements: the array to be sorted
27+
/// - Returns: an array with the same elements but in order
28+
public func BubbleSort<T> (_ elements: [T]) -> [T] where T: Comparable {
29+
var array = elements
30+
31+
for i in 0..<array.count {
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]
36+
array[j] = tmp
37+
}
38+
}
39+
}
40+
41+
return array
42+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

Bubble Sort/MyPlayground.playground/playground.xcworkspace/contents.xcworkspacedata

+7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+
<plist version="1.0">
4+
<dict>
5+
<key>IDEDidComputeMac32BitWarning</key>
6+
<true/>
7+
</dict>
8+
</plist>

Bubble Sort/README.markdown

+114-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Bubble Sort
22

3-
Bubble sort is a sorting algorithm that is implemented by starting in the beginning of the array and swapping the first two elements only if the first element is greater than the second element. This comparison is then moved onto the next pair and so on and so forth. This is done until the array is completely sorted. The smaller items slowly “bubble” up to the beginning of the array.
3+
Bubble sort is a sorting algorithm that is implemented by starting in the beginning of the array and swapping the first two elements only if the first element is greater than the second element. This comparison is then moved onto the next pair and so on and so forth. This is done until the array is completely sorted. The smaller items slowly “bubble” up to the beginning of the array. Sometimes this algorithm is refered as Sinking sort, due to the larger, or heavier elements sinking to the end of the array.
44

55
##### Runtime:
66
- Average: O(N^2)
@@ -12,3 +12,116 @@ Bubble sort is a sorting algorithm that is implemented by starting in the beginn
1212
### Implementation:
1313

1414
The implementation will not be shown as the average and worst runtimes show that this is a very inefficient algorithm. However, having a grasp of the concept will help you understand the basics of simple sorting algorithms.
15+
16+
Bubble sort is a very simple sorting algorithm, it consists in comparing pairs of adjacent elements in the array, if the first element is larger, swap them, otherwise, you do nothing and go for the next comparison.
17+
This is accomplished by looking through the array `n` times, `n` being the amount of elements in the array.
18+
19+
![animated gif of the bubble sort algorithm](https://s3.amazonaws.com/codecademy-content/programs/tdd-js/articles/BubbleSort.gif)
20+
21+
This GIF shows a inverted implementation than
22+
23+
#### Example
24+
Let us take the array `[5, 1, 4, 2, 8]`, and sort the array from lowest number to greatest number using bubble sort. In each step, elements written in bold are being compared. Three passes will be required.
25+
26+
##### First Pass
27+
[ **5 1** 4 2 8 ] -> [ **1 5** 4 2 8 ], Here, algorithm compares the first two elements, and swaps since 5 > 1.
28+
29+
[ 1 **5 4** 2 8 ] -> [ 1 **4 5** 2 8 ], Swap since 5 > 4
30+
31+
[ 1 4 **5 2** 8 ] -> [ 1 4 **2 5** 8 ], Swap since 5 > 2
32+
33+
[ 1 4 2 **5 8** ] -> [ 1 4 2 **5 8** ], Now, since these elements are already in order (8 > 5), algorithm does not swap them.
34+
35+
##### Second Pass
36+
[ **1 4** 2 5 8 ] -> [ **1 4** 2 5 8 ]
37+
38+
[ 1 **4 2** 5 8 ] -> [ 1 **2 4** 5 8 ], Swap since 4 > 2
39+
40+
[ 1 2 **4 5** 8 ] -> [ 1 2 **4 5** 8 ]
41+
42+
[ 1 2 4 **5 8** ] -> [ 1 2 4 **5 8** ]
43+
Now, the array is already sorted, but the algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
44+
45+
##### Third Pass
46+
[ **1 2** 4 5 8 ] -> [ **1 2** 4 5 8 ]
47+
48+
[ 1 **2 4** 5 8 ] -> [ 1 **2 4** 5 8 ]
49+
50+
[ 1 2 **4 5** 8 ] -> [ 1 2 **4 5** 8 ]
51+
52+
[ 1 2 4 **5 8** ] -> [ 1 2 4 **5 8** ]
53+
54+
This is the same for the forth and fifth passes.
55+
56+
#### Code
57+
```swift
58+
for i in 0..<array.count {
59+
for j in 1..<array.count {
60+
if array[j] < array[i] {
61+
let tmp = array[i]
62+
array[i] = array[j]
63+
array[j] = tmp
64+
}
65+
}
66+
}
67+
return array
68+
```
69+
70+
#### Optimization
71+
The bubble sort algorithm can be easily optimized by observing that the `n-th` pass finds the `n-th` largest element and puts it into its final place. So, the inner loop can avoid looking at the last `n-1` items when running for the `n-th` time:
72+
73+
```swift
74+
for i in 0..<array.count {
75+
for j in 1..<array.count - i {
76+
if array[j] < array[i] {
77+
let tmp = array[i]
78+
array[i] = array[j]
79+
array[j] = tmp
80+
}
81+
}
82+
}
83+
return array
84+
```
85+
86+
The only change made was on the second line, changing the interval from `1..<array.count` to `1..<array.count - i`, effectively cutting the number of comparisons by half.
87+
88+
The ordering with the optimized code would look something like this for the array `[5, 1, 4, 2, 8]`:
89+
90+
##### First Pass
91+
[ **5 1** 4 2 8 ] -> [ **1 5** 4 2 8 ], Swaps since 5 > 1
92+
93+
[ 1 **5 4** 2 8 ] -> [ 1 **4 5** 2 8 ], Swap since 5 > 4
94+
95+
[ 1 4 **5 2** 8 ] -> [ 1 4 **2 5** 8 ], Swap since 5 > 2
96+
97+
[ 1 4 2 **5 8** ] -> [ 1 4 2 **5 8** ], Now, since these elements are already in order (8 > 5), algorithm does not swap them.
98+
99+
*by the end of the first pass, the last element is guaranteed to be the largest*
100+
101+
##### Second Pass
102+
[ **1 4** 2 5 8 ] -> [ **1 4** 2 5 8 ]
103+
104+
[ 1 **4 2** 5 8 ] -> [ 1 **2 4** 5 8 ], Swap since 4 > 2
105+
106+
[ 1 2 **4 5** 8 ] -> [ 1 2 **4 5** 8 ], As the first loop has occured once, the inner loop stops here, not comparing 5 with 8
107+
108+
##### Third Pass
109+
[ **1 2** 4 5 8 ] -> [ **1 2** 4 5 8 ]
110+
111+
[ 1 **2 4** 5 8 ] -> [ 1 **2 4** 5 8 ] again, stoping one comparison short
112+
113+
##### Fourth Pass
114+
[ **1 2** 4 5 8 ] -> [ **1 2** 4 5 8 ]
115+
116+
There is no Fifth pass
117+
118+
#### Conclusion
119+
120+
Even with the proposed optimizations, this is still a terribly inefficient sorting algorithm. A good alternative is [Merge Sort](), that not only is better performing, has a similar degree of dificulty to implement.
121+
122+
*Updated for the Swift Algorithm Club by Julio Brazil*
123+
124+
##### Supporting Links
125+
[Code Pumpkin](https://codepumpkin.com/bubble-sort/)
126+
[Wikipedia](https://en.wikipedia.org/wiki/Bubble_sort)
127+
[GeeksforGeeks](https://www.geeksforgeeks.org/bubble-sort/)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+
<plist version="1.0">
4+
<dict>
5+
<key>IDEDidComputeMac32BitWarning</key>
6+
<true/>
7+
</dict>
8+
</plist>

0 commit comments

Comments
 (0)