Skip to content

Instantly share code, notes, and snippets.

@ryasmi
Last active December 15, 2015 16:59
Show Gist options
  • Save ryasmi/5292779 to your computer and use it in GitHub Desktop.
Save ryasmi/5292779 to your computer and use it in GitHub Desktop.
Sorting algorithms written in JavaScript for an assignment at Oxford Brookes University for the Discrete Maths module.
var bubbleSort = function (list) {
var i, temp;
var swapped = true;
var iterations = 0;
var n = list.length;
while (swapped) {
swapped = false;
for (i = 1; i < n; i += 1) {
iterations += 1;
if (list[i - 1] > list[i]) {
temp = list[i];
list[i] = list[i - 1];
list[i - 1] = temp;
swapped = true;
}
}
}
return {"list": list, "iterations": iterations};
};
var insertionSort = function (list) {
var i, insval, inspos;
var iterations = 0;
var n = list.length;
for (i = 1; i <= n - 1; i += 1) {
insval = list[i];
inspos = i;
while (inspos > 0 && insval < list[inspos - 1]) {
iterations += 1;
list[inspos] = list[inspos - 1];
inspos -= 1;
}
iterations += 1;
list[inspos] = insval;
}
return {"list": list, "iterations": iterations};
};
var selectionSort = function (list) {
var j, i, temp;
var iterations = 0;
var minpos = 0;
var n = list.length;
for (j = 0; j < n - 1; j += 1) {
minpos = j;
for (i = j + 1; i < n; i += 1) {
iterations += 1;
if (list[i] < list[minpos]) {
minpos = i;
}
}
if (minpos != j) {
temp = list[j];
list[j] = list[minpos];
list[minpos] = temp;
}
}
return {"list": list, "iterations": iterations};
};
bubbleSort([7, 3, 4, 1, 2, 8, 5, 6]);
insertionSort([7, 3, 4, 1, 2, 8, 5, 6]);
selectionSort([7, 3, 4, 1, 2, 8, 5, 6]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment