Last active
July 22, 2016 10:31
-
-
Save mlvea/924168b045f57f94183908a0bc1010e9 to your computer and use it in GitHub Desktop.
Merge Sort and Quick Sort Algorithms in Swift (https://swift.madnik.space/algorithms-merge-sort-and-quick-sort-in-swift)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func mergeSort<T: Comparable>(inout array:[T],p: Int, r: Int) -> [T]{ | |
var p = p | |
guard r > p else{ | |
return array | |
} | |
var q = p + (r-p)/2 | |
mergeSort(&array, p: p, r: q) | |
mergeSort(&array, p: q+1, r: r) | |
//Now Merge | |
while q < r && p <= q { | |
if array[p] > array[q+1]{ | |
array.insert(array.removeAtIndex(q+1), atIndex: p) | |
if q < r { q+=1 } | |
} | |
if p <= q { p += 1 } | |
} | |
return array | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func quickSort<T where T:Comparable>(inout array: [T],p: Int,r: Int) -> [T]{ | |
guard array[p...r].count > 1 else{ | |
return array | |
} | |
func partition<T where T:Comparable>(inout array: [T],pivotIndex: Int) -> Int{ | |
var q = p | |
var i = p | |
let pivot = array[pivotIndex] | |
while i < r{ | |
if array[i] < pivot { | |
array.insert(array.removeAtIndex(i), atIndex: q) | |
q += 1 | |
} | |
i += 1 | |
} | |
array.insert(array.removeAtIndex(pivotIndex), atIndex: q) | |
return q | |
} | |
let q = partition(&array, pivotIndex: r) | |
if p < q-1 { quickSort(&array, p: p, r: q-1) } | |
if q+1 < r { quickSort(&array, p: q+1, r: r) } | |
return array | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Gist contains the sample code used in article https://swift.madnik.space/algorithms-merge-sort-and-quick-sort-in-swift/index.html