Created
December 18, 2017 14:35
-
-
Save scriptonian/0a8e4c1602cc6f461769a6e9a5a368d6 to your computer and use it in GitHub Desktop.
Javscript Quick 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
function ScriptoniteSort() { | |
this.arr = []; | |
} | |
ScriptoniteSort.prototype = { | |
swap: function(arr, index_one, index_two) { | |
//swap | |
var temp = arr[index_one]; | |
arr[index_one] = arr[index_two]; | |
arr[index_two] = temp; | |
}, | |
validateCollection: function(datalist) { | |
if(arguments.length === 0 || !Array.isArray(this.arr)) { | |
throw new Error('Either No Arguments Passed, Or Passed Param is not an Array'); | |
} | |
}, | |
partition: function(datalist, low, high) { | |
var pivot = datalist[low]; | |
while(low <= high) { | |
while(datalist[low] < pivot) { | |
low++; | |
} | |
while(datalist[high] > pivot){ | |
high--; | |
} | |
if(low <= high) { | |
this.swap(datalist, low, high); | |
low++; | |
high--; | |
} | |
} | |
return low; | |
}, | |
quickRecursion: function(datalist, low, high) { | |
//return if low is greater or equal to hight | |
if(low > high) { return; } | |
//set high and low marks | |
var pivotPoint; | |
pivotPoint = this.partition(datalist, low, high); | |
if(low < pivotPoint - 1){ | |
this.quickRecursion(datalist, low, pivotPoint - 1); | |
} | |
if(pivotPoint < high) { | |
this.quickRecursion(datalist, pivotPoint, high); | |
} | |
}, | |
quickSort : function(datalist) { | |
var low = 0, | |
high = datalist.length -1; | |
this.quickRecursion(datalist, low, high); | |
//display final results | |
console.log(datalist); | |
} | |
};//prototype end | |
//var myArr = [9, 11, 5, 1, 7, 2, 15, 1, 8, 6]; | |
var myArr = [6000, 34, 203, 3, 746, 200, 984, 198, 764, 1, 9, 1]; | |
//var myArr = [1, 7, 4, 0, 5, 3]; | |
//var myArr = [64, 25, 12, 22, 11]; | |
var collection = new ScriptoniteSort(); | |
collection.quickSort(myArr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment