Last active
December 17, 2015 03:59
-
-
Save kanghyojun/5547195 to your computer and use it in GitHub Desktop.
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
Array.prototype.swap = function(a, b) { | |
var tmp = this[a]; | |
this[a] = this[b]; | |
this[b] = tmp; | |
}; | |
Array.prototype.qsort = function(key) { | |
if(key === void 0) { | |
key = function(x) { | |
return x; | |
}; | |
} | |
var findPivot = function(a, left, right) { | |
var mid = Math.floor(left + (right-left) / 2) | |
pivotIndex = null; | |
if(a[left] < a[mid] && a[mid] < a[right]) { | |
pivotIndex = mid | |
} else if(a[left] < a[right]) { | |
pivotIndex = left | |
} else { | |
pivotIndex = right | |
} | |
return pivotIndex; | |
}, | |
partition = function(a, l, r, p) { | |
var storeIndex = l, | |
pivot = key(a[p]); | |
a.swap(p, r); | |
for(i = l; i <= r - 1; i++) { | |
if(key(a[i]) <= pivot) { | |
a.swap(i, storeIndex); | |
storeIndex = storeIndex + 1; | |
} | |
} | |
a.swap(storeIndex, r); | |
return storeIndex; | |
}, | |
qsort = function(l, left, right) { | |
if(left < right) { | |
var pivotIndex = findPivot(l, left, right); | |
var newPivotIndex = partition(l, left, right, pivotIndex); | |
qsort(l, left, newPivotIndex - 1); | |
qsort(l, newPivotIndex + 1, right); | |
} | |
}; | |
qsort(this, 0, this.length - 1); | |
return this; | |
} | |
var a = [1,4,2,3]; | |
console.log(a); | |
console.log(a.qsort(function(x) { return x['a'] })); | |
var b = [{'a': 4}, {'a': 2}, {'a': 3}, {'a': 1}]; | |
console.log(b); | |
console.log(b.qsort(function(x) { return x[1] })) | |
var c = [["a", 1], ["b", 2], ["c", 4], ["d", 3]]; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment