Skip to content

Instantly share code, notes, and snippets.

@tsongas
Created November 20, 2014 05:10
Show Gist options
  • Save tsongas/07f9bd5d410f83802c8f to your computer and use it in GitHub Desktop.
Save tsongas/07f9bd5d410f83802c8f to your computer and use it in GitHub Desktop.
Selection Sort Example
$(document).ready(function() {
var numbers = [];
console.log(numbers);
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
sleep(1000);
// sort numbers using bubble sort, selection sort,
// insertion sort or quicksort
var i, j;
var iMin;
/* advance the position through the entire array */
/* (could do j < n-1 because single element is also min element) */
for (j = 0; j < numbers.length - 1; j++) {
/* find the min element in the unsorted a[j .. n-1] */
/* assume the min is the first element */
iMin = j;
/* test against elements after j to find the smallest */
for ( i = j+1; i < numbers.length; i++) {
/* if this element is less, then it is the new minimum */
if (numbers[i] < numbers[iMin]) {
/* found new minimum; remember its index */
iMin = i;
}
}
if(iMin != j) {
// swap(a[j], a[iMin]);
// A[x] = A.splice(y, 1, A[x])[0];
numbers[j] = numbers.splice(iMin, 1, numbers[j])[0];
}
}
console.log(numbers);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sort</title>
<link rel="stylesheet" href="style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
</body>
</html>
// css would go here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment