JSFiddle - React, Tailwind, and code Playground
by hesster92
HTML
<h3>
Assignment 8: Sorting</h3>
<br>
<input type="button" value="Create List" onclick="populate()">
<input type="button" value="Merge Sort" onclick="startMerge()">
<input type="button" value="Bubble Sort" onclick="list1.bubbleSort()">
<br>
<br>
<input type="textbox" id="input">
<br>
<br>
<input type="button" value="Insert String (adds to bottom)" onclick="insertInput()">
<br><br>
<div id="output">
</div>
JavaScript
function LinkedList() {
this.length = 0;
this.head = null;
this.tail = null;
}
function Node() {
this.next = null;
this.previous = null;
this.element = null;
}
LinkedList.prototype.add = function(element) {
let node = new Node();
node.element = element;
if (this.head === null) {
this.head = node;
this.length = 1;
return node;
}
if (this.tail === null) {
this.tail = node;
this.tail.previous = this.head;
this.head.next = this.tail;
this.length = 2;
return node;
}
this.tail.next = node;
node.previous = this.tail;
this.tail = node;
this.length += 1;
return node;
}
LinkedList.prototype.print = function() {
let i = "";
let node = this.head;
while (node != null) {
i += node.element + "<br> ";
node = node.next;
}
return i;
}
LinkedList.prototype.dequeue = function() {
if (this.head == this.tail) {
var current = this.head;
this.head = null;
this.tail = null;
this.length = 0;
return current.element;
}
var previous = this.head;
this.head = this.head.next;
this.length -= 1;
return previous.element;
}
LinkedList.prototype.insertString = function(item) {
if (this.head == null) {
this.add(item);
}
var node = new Node();
node.element = item;
if (item < this.head.element) {
this.head.previous = node;
node.next = this.head;
this.head = node;
}
if (item > this.tail.element) {
this.tail.next = node;
this.tail = this.tail.next;
}
var c = this.head;
while (c.next != null) {
if ((item > c.element) && (item < c.next.element)) {
node.previous = c;
node.next = c.next;
c.next.previous = node;
c.next = node;
}
c = c.next;
}
}
function populate() {
list1 = new LinkedList();
for (var i = 0; i <= 20; i++) {
let r = Math.random().toString(36).substring(7);
list1.add(r);
}
document.getElementById("output").innerHTML = list1.print();
}
function mergeSort(list) {
if...