Created
April 15, 2014 21:41
-
-
Save lawrencejones/10779033 to your computer and use it in GitHub Desktop.
Implementation of a merge sort
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
| PASSED = 0 | |
| check_sorted = (was, now) -> | |
| if !now.reduce ((a,c,i) -> a && (!now[i+1]? || now[i] < now[i+1])), true | |
| throw new Error """\n | |
| Was: [#{was}] | |
| Now: [#{now}]\n""" | |
| else | |
| ++PASSED | |
| Array::shuffle = -> | |
| r = []; iss = [0..@length - 1] | |
| while iss[0]? | |
| i = Math.floor(Math.random()*iss.length) | |
| r.push @[iss.splice i, 1] | |
| r | |
| Array::mergeSort = -> | |
| conquer = (p, q, r) => | |
| while p <= q && q < r | |
| if @[p++] > @[q+1] | |
| @splice (p-1), 0, (@splice (q++ +1), 1)[0] | |
| divide = (p = 0, r = @length - 1) => | |
| if p < r | |
| q = Math.floor (p + r)/2 | |
| divide p, q | |
| divide q+1, r | |
| conquer p, q, r | |
| do divide; @ | |
| for i in [1..5000] | |
| sample = [1..Math.ceil(Math.random()*20)].shuffle() | |
| check_sorted sample[..], sample.mergeSort() | |
| console.log "PASSED #{PASSED} tests." | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment