Module 7 A1
Sorting Part 1
by Jenni Meiklejohn
HTML
<h1><center> Module 7 Assignment 1</center></h1>
<h2><center> Sorting </center></h2>
<input type="textbox" id="newNode" size="5" />
<input type="button" class="button" id="addNode" value="Insert String" onClick="insertString();" />
<br>
<input type="button" class="button" id="repop" value="Randomized String list" onClick="fillStack();" />
<input type="button" class="button" value="Merge Sort" onClick="mergeSorted()" />
<input type="button" class="button" value="Bubble Sort" onClick="bubblesorted();" />
<p id="l"> </p>
<p id="m"> </p>
<p id="r"> </p>
<p id="output"> </p>
JavaScript
var Node = function(_content) {
this.next = null;
this.previous = null;
this.content = _content;
}
var Stack = function() {
this.top = null;
this.bottom = null;
this.push = function(_content) {
if (this.bottom == null) {
this.bottom = new Node(_content);
this.top = this.bottom;
return this;
}
var addedNode = new Node(_content);
addedNode.last = this.top;
this.top.next = addedNode;
this.top = addedNode;
}
this.toString = function() {
var d = "";
var node = this.bottom;
while (node != null) {
d += node.content + "<br/>";
node = node.next;
}
return d;
}
}
var Chain = new Stack();
function fillStack() {
for (i = 1; i <= 10; i++) {
Chain.push(randomString());
document.getElementById("l").innerHTML += text + "<br/>";
}
}
function randomString() {
var charOptions = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+,./<>?;':";
text = "";
for (var i = 0; i < 5; i++)
text += charOptions.charAt(Math.floor(Math.random() * charOptions.length));
return text;
}
function insertString() {
var value = document.getElementById('newNode').value;
Chain.push(value);
document.getElementById('l').innerHTML += value + "<br/>";
}
function bubblesorted() {
a = Chain.toString().split("<br/>");
bubbleSort(a);
for (var i = 0; i < a.length; i++) {
document.getElementById('m').innerHTML += a[i] + "<br/>";
}
}
function bubbleSort(a) {
var swapped;
do {
swapped = false;
for (var i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
var temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
swapped = true;
}
}
} while (swapped);
}
function mergeSort(v) {
if (v.length < 2) return v;
var m = parseInt(v.length / 2);
var l = v.slice(0, m);
var r = v.slice(m, v.length);
return merge(mergeSort(l), mergeSort(r));
}
function merge(l, r) {
result = [];
while (l.length && r.length) {
...