Created
September 25, 2020 15:43
-
-
Save jessicabuzzelli/c71f0db72e22dc320cdf6bc0211c4d32 to your computer and use it in GitHub Desktop.
Merge Sort in Julia.
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
| function mergesort(x::Array) | |
| """ | |
| x: 1-dimensional array to be sorted in ascending order | |
| """ | |
| n = length(x) | |
| sorted_arr = [] | |
| if n > 1 | |
| k = floor(Int, n / 2) | |
| left = mergesort(x[1:k]) | |
| right = mergesort(x[k+1:n]) | |
| sorted_arr = merge(left, right) | |
| else | |
| return x | |
| end | |
| return sorted_arr | |
| end; | |
| function merge(left::Array, right::Array) | |
| if left == [] && right != [] | |
| return right | |
| elseif right == [] | |
| return left | |
| end | |
| l = length(left) | |
| r = length(right) | |
| i = 1 | |
| j = 1 | |
| combined = [] | |
| while true | |
| if left[i] <= right[j] | |
| append!(combined, left[i]) | |
| i += 1 | |
| else | |
| append!(combined, right[j]) | |
| j += 1 | |
| end | |
| if i > l && j <= r | |
| return append!(combined, right[j:r]) | |
| elseif j > r && i <= l | |
| return append!(combined, left[i:l]) | |
| elseif i > l && j > r | |
| return combined | |
| end | |
| end | |
| end; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment