Skip to content

Commit

Permalink
Merge pull request kodecocodes#824 from JulioBBL/bubble-sort
Browse files Browse the repository at this point in the history
Add convenience method to Bubble Sort
  • Loading branch information
richard-ash authored Dec 19, 2018
2 parents cf7aec2 + 299a67c commit dd42021
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
4 changes: 3 additions & 1 deletion Bubble Sort/MyPlayground.playground/Contents.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@ import Foundation
var array = [4,2,1,3]

print("before:",array)
print("after:",BubbleSort(array))
print("after:", bubbleSort(array))
print("after:", bubbleSort(array, <))
print("after:", bubbleSort(array, >))
10 changes: 7 additions & 3 deletions Bubble Sort/MyPlayground.playground/Sources/BubbleSort.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,18 @@ import Foundation

/// Performs the bubble sort algorithm in the array
///
/// - Parameter elements: the array to be sorted
/// - Parameter elements: a array of elements that implement the Comparable protocol
/// - Returns: an array with the same elements but in order
public func BubbleSort<T> (_ elements: [T]) -> [T] where T: Comparable {
public func bubbleSort<T> (_ elements: [T]) -> [T] where T: Comparable {
return bubbleSort(elements, <)
}

public func bubbleSort<T> (_ elements: [T], _ comparison: (T,T) -> Bool) -> [T] {
var array = elements

for i in 0..<array.count {
for j in 1..<array.count-i {
if array[j] < array[j-1] {
if comparison(array[j], array[j-1]) {
let tmp = array[j-1]
array[j-1] = array[j]
array[j] = tmp
Expand Down

0 comments on commit dd42021

Please sign in to comment.