Assignment 8 - Sorting
by aren_anderson
HTML
<h2>
Sorting Values
</h2>
<h4>
Enter a string: <input type="textbox" id="tbString" value="Enter text here" />
</h4>
<input type="button" value="Generate List" id="btnGenerate" />
<input type="button" value="Add String" id="btnAdd" />
<input type="button" value="Bubble Sort" id="btnBubble" />
<input type="button" value="Merge Sort" id="btnMerge" />
<br/><br/>
<table>
<tr>
<th>Generated List</th>
<th>Merged List</th>
<th>Bubble List</th>
</tr>
<tr>
<td>
<div id="generatedList"></div>
</td>
<td>
<div id="mergedList"></div>
</td>
<td>
<div id="bubbleList"></div>
</td>
</tr>
</table>
CSS
table,
th,
td {
border: 1px solid black;
}
JavaScript
function List(){
this.head = null;
this.length = 0;
}
function Node(_item){
this.next = null;
this.value = _item;
}
List.prototype.push = function(_item){
var node = new Node(_item);
let currentNode = this.head;
if (currentNode == null){
this.head = node;
this.length++;
return node;
}
while (currentNode.next){
currentNode = currentNode.next;
}
currentNode.next = node;
this.length++;
return node;
}
List.prototype.pop = function(){
var length = this.length;
if (this.head == null){
return null;
}
var popped = this.head;
this.head = this.head.next;
this.length--;
return popped.value;
}
var list = new List();
function sortByMerge(_list){
var length = _list.length;
if(length < 2){
return _list;
}
var list1 = new List();
var list2 = new List();
var i = 0;
var node = _list.head;
while(node != null){
if(i < length/2){
list1.push(node.value);
}else{
list2.push(node.value);
}
i++;
node = node.next;
}
return merge(sortByMerge(list1), sortByMerge(list2));
}
function merge(list1, list2){
var mergedList = new List();
while ((list1.head != null) && (list2.head != null)){
if (list1.head.value <= list2.head.value){
mergedList.push(list1.pop())
}else{
mergedList.push(list2.pop());
}
}
while (list1.head != null){
mergedList.push(list1.pop());
}
while (list2.head != null){
mergedList.push(list2.pop());
}
return mergedList;
}
function sortByBubble(_list){
var j = _list.head;
var k = j.next;
for (j = _list.head; j!= null; j = j.next){
for (k = j.next; k != null; k = k.next){
if (j.value > k.value){
let t = j.value;
j.value = k.value;
k.value = t;
}
}
}
return _list;
}
document.getElementById("btnGenerate").onclick = function(){
let d = "";
for (var n = 1; n<= 20; n++){
var random = "";
var alphabet = "abcdefghijklmnopqrstuvwxyz";
for(var c = 0; c <= 5; c++){
...