Skip to content

Instantly share code, notes, and snippets.

@xypaul
Created May 28, 2015 02:03
Show Gist options
  • Save xypaul/a8f482ead136cb83332f to your computer and use it in GitHub Desktop.
Save xypaul/a8f482ead136cb83332f to your computer and use it in GitHub Desktop.
Improved Quick Sort Algorithm in JavaScript
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<script id="jsbin-javascript">
function quickSort(array, start, end) {
if (start === undefined || end === undefined) {
var start = 0;
var end = array.length - 1;
}
var pivot = Math.floor(start + (end - start)/2);
var i = start;
var j = end;
while (i<=j) {
while (array[i] < array[pivot]) {
i++;
}
while (array[j] > array[pivot]) {
j--;
}
if (i <= j) {
var temp = array[i]
array[i] = array[j];
array[j] = temp;
j--;
i++;
}
}
if (start < j) {
array = quickSort(array, start, j);
}
if (end > i) {
array = quickSort(array, i, end);
}
console.log(array)
return array
}
console.log(quickSort([2,4,5,1,2,3]));
</script>
<script id="jsbin-source-javascript" type="text/javascript">
function quickSort(array, start, end) {
if (start === undefined || end === undefined) {
var start = 0;
var end = array.length - 1;
}
var pivot = Math.floor(start + (end - start)/2);
var i = start;
var j = end;
while (i<=j) {
while (array[i] < array[pivot]) {
i++;
}
while (array[j] > array[pivot]) {
j--;
}
if (i <= j) {
var temp = array[i]
array[i] = array[j];
array[j] = temp;
j--;
i++;
}
}
if (start < j) {
array = quickSort(array, start, j);
}
if (end > i) {
array = quickSort(array, i, end);
}
console.log(array)
return array
}
console.log(quickSort([2,4,5,1,2,3]));</script></body>
</html>
function quickSort(array, start, end) {
if (start === undefined || end === undefined) {
var start = 0;
var end = array.length - 1;
}
var pivot = Math.floor(start + (end - start)/2);
var i = start;
var j = end;
while (i<=j) {
while (array[i] < array[pivot]) {
i++;
}
while (array[j] > array[pivot]) {
j--;
}
if (i <= j) {
var temp = array[i]
array[i] = array[j];
array[j] = temp;
j--;
i++;
}
}
if (start < j) {
array = quickSort(array, start, j);
}
if (end > i) {
array = quickSort(array, i, end);
}
console.log(array)
return array
}
console.log(quickSort([2,4,5,1,2,3]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment