Last active
September 11, 2017 19:10
-
-
Save Nitesh-Mishra/89a5e148f6b775a33acfbe5e7c3b0f34 to your computer and use it in GitHub Desktop.
Merge Sort program in ruby
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
| # merge_sort.rb | |
| # | |
| # $ ruby merge_sort.rb | |
| # [1, 2, 3, 4, 5, 6, 7, 8] | |
| def merge_sort(array) | |
| n = array.length | |
| if n > 1 | |
| mid = n/2 | |
| lefthalf = array[0..mid-1] | |
| righthalf = array[mid..n-1] | |
| merge_sort lefthalf | |
| merge_sort righthalf | |
| i = j = k = 0 | |
| while i < lefthalf.length and j < righthalf.length | |
| if lefthalf[i] < righthalf[j] | |
| array[k] = lefthalf[i] | |
| i = i+1 | |
| else | |
| array[k] = righthalf[j] | |
| j = j+1 | |
| end | |
| k += 1 | |
| end | |
| while i < lefthalf.length | |
| array[k] = lefthalf[i] | |
| i = i+1 | |
| k = k+1 | |
| end | |
| while j < righthalf.length | |
| array[k] = righthalf[j] | |
| j = j+1 | |
| k = k+1 | |
| end | |
| end | |
| end | |
| print array = [6,5,3,1,8,7,2,4] | |
| merge_sort array | |
| print array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment