File tree 2 files changed +10
-4
lines changed
Bubble Sort/MyPlayground.playground
2 files changed +10
-4
lines changed Original file line number Diff line number Diff line change @@ -3,4 +3,6 @@ import Foundation
3
3
var array = [ 4 , 2 , 1 , 3 ]
4
4
5
5
print ( " before: " , array)
6
- print ( " after: " , BubbleSort ( array) )
6
+ print ( " after: " , bubbleSort ( array) )
7
+ print ( " after: " , bubbleSort ( array, < ) )
8
+ print ( " after: " , bubbleSort ( array, > ) )
Original file line number Diff line number Diff line change @@ -23,14 +23,18 @@ import Foundation
23
23
24
24
/// Performs the bubble sort algorithm in the array
25
25
///
26
- /// - Parameter elements: the array to be sorted
26
+ /// - Parameter elements: a array of elements that implement the Comparable protocol
27
27
/// - Returns: an array with the same elements but in order
28
- public func BubbleSort< T> ( _ elements: [ T ] ) -> [ T ] where T: Comparable {
28
+ public func bubbleSort< T> ( _ elements: [ T ] ) -> [ T ] where T: Comparable {
29
+ return bubbleSort ( elements, < )
30
+ }
31
+
32
+ public func bubbleSort< T> ( _ elements: [ T ] , _ comparison: ( T , T ) -> Bool ) -> [ T ] {
29
33
var array = elements
30
34
31
35
for i in 0 ..< array. count {
32
36
for j in 1 ..< array. count- i {
33
- if array [ j] < array [ j- 1 ] {
37
+ if comparison ( array [ j] , array [ j- 1 ] ) {
34
38
let tmp = array [ j- 1 ]
35
39
array [ j- 1 ] = array [ j]
36
40
array [ j] = tmp
You can’t perform that action at this time.
0 commit comments