Created
April 7, 2014 14:23
-
-
Save adnils/10021233 to your computer and use it in GitHub Desktop.
quicksort visualised with javascript canvas (WIP)
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>i wish this was hungarian folk dance</title> | |
</head> | |
<body> | |
<canvas id="a" width="1280" height="720"></canvas> | |
<script> | |
// CANVAS | |
var a_canvas = document.getElementById("a"); | |
var context = a_canvas.getContext("2d"); | |
for (var x = 0.5; x < 1280; x += 10) { | |
context.moveTo(x, 0); | |
context.lineTo(x, 720); | |
} for (var y = 0.5; y < 720; y += 10) { | |
context.moveTo(0, y); | |
context.lineTo(1280, y); | |
} | |
context.strokeStyle = "#eee"; | |
context.stroke(); | |
// QUICKSORT | |
function quickSort(items, left, right) { | |
var index; | |
if (items.length > 1) { | |
left = typeof left != "number" ? 0 : left; | |
right = typeof right != "number" ? items.length - 1 : right; | |
index = partition(items, left, right); | |
if (left < index - 1) { | |
quickSort(items, left, index - 1); | |
} | |
console.log (items); | |
if (index < right) { | |
quickSort(items, index, right); | |
} | |
console.log (items); | |
} | |
return items; | |
} | |
function partition(items, left, right) { | |
var pivot = items[Math.floor((right + left) / 2)], | |
i = left, | |
j = right; | |
while (i <= j) { | |
while (items[i] < pivot) { | |
i++; | |
} | |
while (items[j] > pivot) { | |
j--; | |
} | |
if (i <= j) { | |
swap(items, i, j); | |
i++; | |
j--; | |
} | |
} | |
return i; | |
} | |
function swap(items, firstIndex, secondIndex){ | |
var temp = items[firstIndex]; | |
items[firstIndex] = items[secondIndex]; | |
items[secondIndex] = temp; | |
} | |
var items = []; | |
for (var i = 100; i > 0; i--) { | |
items.push (Math.floor(Math.random()*200+1)); | |
} | |
// first call | |
var result = quickSort(items); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment