Created
July 16, 2016 00:29
-
-
Save jose-roberto-abreu/a15b76c97ac841bd5fba18e6c43c2879 to your computer and use it in GitHub Desktop.
MergeSort
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(var values:[Int])->[Int]{ | |
if(values.count <= 1){ | |
return values; | |
} | |
if(values.count == 2){ | |
if(values[0] > values[1]){ | |
swap(&values[0],&values[1]) | |
} | |
return values | |
} | |
let mid = Int(values.count / 2) | |
var leftArr = mergeSort(Array(values[0...mid-1])) | |
var rightArr = mergeSort(Array(values[mid...values.count-1])) | |
var result:[Int] = [] | |
let size = leftArr.count + rightArr.count | |
var i = 0 | |
var j = 0 | |
for(var k=0;i<size;k += 1){ | |
if i >= leftArr.count{ | |
result = result + Array(rightArr[j...rightArr.count-1]) | |
break | |
} | |
if j >= rightArr.count{ | |
result = result + Array(leftArr[i...leftArr.count-1]) | |
break | |
} | |
if rightArr[j] <= leftArr[i]{ | |
result.append(rightArr[j]) | |
j += 1 | |
continue | |
} | |
result.append(leftArr[i]) | |
i += 1 | |
} | |
return result; | |
} | |
print(mergeSort([2,0,4,6,5,3])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment