JSFiddle - React, Tailwind, and code Playground
by puuga
HTML
<body>
<h1>Quick Sort Algorithm</h1>
<div>list: <input id="inputList" onkeyup="goSort()" value="4,7,1,3,2,6,5"/></div>
<h2>Output</h2>
<div id="output"></div>
</body>
CSS
body {
margin: 10px;
font-family: Helvetica;
}
h1 {
font-size: 140%;
margin-bottom: 20px;
}
h2 {
font-size: 110%;
margin: 10px 0;
}
JavaScript
//Quick Sort Algorithm
function doSwap(arr, i, j) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
function partition(list, leftIndex, rightIndex) {
var pivotKey = list[parseInt((leftIndex + rightIndex) / 2, 10)];
while (leftIndex <= rightIndex) {
while (list[leftIndex] < pivotKey) {
leftIndex++;
}
while (list[rightIndex] > pivotKey) {
rightIndex--;
}
if (leftIndex <= rightIndex) {
doSwap(list, leftIndex, rightIndex);
leftIndex++;
rightIndex--;
}
}
return leftIndex;
}
function quickSort(list, leftIndex, rightIndex) {
var pivotKey = partition(list, leftIndex, rightIndex);
//alert(list);
if (leftIndex < pivotKey - 1) {
quickSort(list, leftIndex, pivotKey - 1);
}
if (pivotKey < rightIndex) {
quickSort(list, pivotKey, rightIndex);
}
}
function goSort() {
// Input
var inputList = $('#inputList').val().split(",");
var key = $("#key").val();
// Algorithm
// array in java script is leference type
quickSort(inputList, 0, inputList.length - 1);
// Output
$("#output").html(inputList.join(","));
}