Last active
August 29, 2015 14:12
-
-
Save petomalina/a57a26a10fd751633d41 to your computer and use it in GitHub Desktop.
GSort - simple sorting algorithm
This file contains 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
### | |
Sorting algorithm created by Gelidus January 1st | |
This algorithms uses two cycles to sort the given array correctly. | |
First, it will partially sort given sequence to the subsequences. | |
After that, it will simply compare first element with others to | |
correct the partial sort | |
@author: Peter "Gelidus" Malina - gelidus@hotmail.sk | |
@license: Do what you want | |
### | |
gsort = (sequence = []) -> | |
if sequence.length <= 1 | |
return sequence | |
partialSort = [] | |
first = sequence[0] | |
second = null | |
# partial sort | |
for i in [1..sequence.length-1] | |
second = sequence[i] | |
if first < second | |
partialSort.push(first) | |
first = second # change for the next iteration | |
else | |
partialSort.push(second) | |
partialSort.push(first) # push remaining element | |
totalSort = [partialSort[0]] | |
# total sort | |
for i in [1..partialSort.length-1] | |
if totalSort[0] > partialSort[i] | |
totalSort.unshift(partialSort[i]) | |
else if totalSort[totalSort.length - 1] < partialSort[i] | |
totalSort.push(partialSort[i]) | |
else # fallback to find where it belongs | |
for x in [0..totalSort.length-2] | |
if totalSort[x] < partialSort[i] and totalSort[x+1] > partialSort[i] | |
totalSort.splice(x+1, 0, partialSort[i]) | |
break | |
return totalSort | |
console.log(gsort([6,5,4,3,2,1])) | |
console.log(gsort([2,4,3,1,7,5,6])) | |
console.log(gsort([2,2,1,3,5,6])) | |
console.log(gsort([9,8,7,6,5])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment