Skip to content

Commit dd42021

Browse files
authored
Merge pull request kodecocodes#824 from JulioBBL/bubble-sort
Add convenience method to Bubble Sort
2 parents cf7aec2 + 299a67c commit dd42021

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

Bubble Sort/MyPlayground.playground/Contents.swift

+3-1
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,6 @@ import Foundation
33
var array = [4,2,1,3]
44

55
print("before:",array)
6-
print("after:",BubbleSort(array))
6+
print("after:", bubbleSort(array))
7+
print("after:", bubbleSort(array, <))
8+
print("after:", bubbleSort(array, >))

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

+7-3
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,18 @@ import Foundation
2323

2424
/// Performs the bubble sort algorithm in the array
2525
///
26-
/// - Parameter elements: the array to be sorted
26+
/// - Parameter elements: a array of elements that implement the Comparable protocol
2727
/// - 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] {
2933
var array = elements
3034

3135
for i in 0..<array.count {
3236
for j in 1..<array.count-i {
33-
if array[j] < array[j-1] {
37+
if comparison(array[j], array[j-1]) {
3438
let tmp = array[j-1]
3539
array[j-1] = array[j]
3640
array[j] = tmp

0 commit comments

Comments
 (0)