Big O assignment 2

by austinmillett

HTML

<h1>
Assignment 2 - Austin Millett <!--Heading for assignment-->
</h1>

<br><b>
Enter Array Size:</b><input type="number" id="size">
<button id="createArray">Create Array</button><br><br>
<!--Create Array button created-->

<b>Enter value to find:</b><input type="number" id="searchForValue"><button id="searchArray">Search Array</button><br>
<!--Search Array button created-->

<br><b>Enter location:</b><input type="number" id="index"><br>

<b>Enter value to insert:</b><input type="number" id="insertValue"><button id="insertIntoArray">Insert Into Array</button><br>
<!--Insert Into Array button created for both location and value inserts-->

JavaScript

var array;//Gloabalizing array

document.getElementById("createArray").addEventListener("click", 
function() {
printResults("Created Array: "); //prints the random array of the size entered by user
var size = document.getElementById("size").value;
array = new Array(size);
for(var i = 0; i < size; i++) {
array[i] = Math.floor(Math.random() * 100) + 1;
}

printResults(" " + array.join());
});
document.getElementById("insertIntoArray").addEventListener("click",

function() {
if(array == undefined) {
return;
}

var index = document.getElementById("index").value;
var number = document.getElementById("insertValue").value;
InsertIntoArray(array, index, number);
});

//New function for value insert
function InsertIntoArray(arr, index, number) {
var count = 0;
for(var i = arr.length - 1; i > index; i--) {
arr[i] = arr[i-1];
count++;
}
arr[index] = number;
printResults("Value " + number + " inserted at location: " + index + ", " + count + " operations were performed in this search");
printResults("Time complexity is O(n)");
}

document.getElementById("searchArray").addEventListener("click", function() {
if(array == undefined) {
return;
}
var searchForValue = document.getElementById("searchForValue").value;
searchIntoArray(array, searchForValue);
});

//New function for searching the array
function searchIntoArray(arr, searchForValue) {
var count = 0;
for(var i = 0; i<arr.length; i++) {
count++;
if(arr[i] == searchForValue) {
printResults("Value " + searchForValue + " found at location: " + i + ", " + count + " operations were performed in this search");
printResults("The time complexity is O(n)");
return;
}
}

printResults("Value " + searchForValue + " not found in array, " + count + " operations were performed in this search");
printResults("Time complexity is O(n)");
}

//New function to print results 
function printResults(str) {
var text = document.createTextNode(str);
var par =...