Created
March 19, 2019 15:09
-
-
Save zeeshan1112/9fa224fa5f236c9e0e3e8dc2d07941c5 to your computer and use it in GitHub Desktop.
#Quick sort in javascript
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 Array(arr){ | |
this.arr = arr; | |
}; | |
Array.prototype.doQuickSort = function(low, high) { | |
if(low < high) { | |
var pi = this.partition(low, high); | |
this.doQuickSort(low, pi-1); | |
this.doQuickSort(pi+1, high); | |
} | |
return this.arr; | |
} | |
Array.prototype.partition = function(low, high) { | |
var pivot = this.arr[high]; | |
var i = low-1; | |
for(var j = low; j<high-1; j++) { | |
if(this.arr[j] < pivot) { | |
i++; | |
[this.arr[i],this.arr[j]] = [this.arr[j],this.arr[i]]; | |
} | |
} | |
[this.arr[i+1], this.arr[high]] = [this.arr[high], this.arr[i+1]]; | |
return i+1; | |
} | |
//test QuickSort | |
var arr = [7,5,3,8,6]; | |
var testArray = new Array(arr); | |
console.log(testArray.doQuickSort(0, arr.length-1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another implementation with O(n) extra space