Created
July 16, 2016 00:37
-
-
Save jose-roberto-abreu/6ffaa4df6ceb1085cd0fdaeaeb6c3193 to your computer and use it in GitHub Desktop.
More Efficient, do not recreate the result 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 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.appendContentsOf(Array(rightArr[j...rightArr.count-1])) | |
break | |
} | |
if j >= rightArr.count{ | |
result.appendContentsOf(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