JSFiddle - React, Tailwind, and code Playground
by Peyton Hessler
HTML
<h1>COP3530 MODULE 1.1 / 1.2<br>Functions <BR>InsertIntoArray and Array Search</h1>
<h3 id="theArray"></h3>
<HR>Enter number of array elements
<BR>
<input type="text" id="arrayElements" value="1000"></input>
<button type="button" id="LoadArray" onclick="LoadArray()">Load Array</button>
<BR>
<BR>
<BR>Enter insertion position
<BR>
<input type="text" id="inPosition" value="0"></input>
<button type="button" id="InsertIntoArray" onclick="InsertIntoArray(globalArray)">Insert Into Array</button>
<BR>Enter a value to insert
<BR>
<input type="text" id="inValue" value="0"></input>
<BR>
<BR>
<BR>Enter a value to search for
<BR>
<input type="text" id="searchValue" value="0"></input>
<button type="button" id="Search" onclick="SearchArray()">Search Array</button>
<HR>
<p id="theOutput2"></p>
<HR>
<p id="theOutput"></p>
JavaScript
var numOfOps = 1;
var searchVal = 0;
var globalArray = [];
function LoadArray() {
stats = "";
numElements = document.getElementById("arrayElements").value;
var numArray = [];
for (i = 0; i < numElements; i++) {
numArray[i] = Math.ceil(Math.random() * 100);
}
document.getElementById("theOutput").innerHTML = numArray.join(" | ");
numOfOps=4+i;
stats = numElements + " elements were populated with random numbers (1-100).";
stats += "<BR><BR> There were " + numOfOps + " operations in this process.";
stats += "<BR><BR>This array operaition function represents an O(n) complexity algorithm.";
document.getElementById("theOutput2").innerHTML = stats;
numOfOps = 1;
globalArray = numArray;
}
function InsertIntoArray(varArray) {
var stats = "";
Index = document.getElementById("inPosition").value;
dVal = document.getElementById("inValue").value;
if (Index >= 0 && Index < varArray.length) {
for (i = varArray.length - 1; i > Index; i--) {
varArray[i] = varArray[i - 1];
numOfOps++;
}
} else {
alert("Invalid index!");
return;
}
globalArray[Index] = dVal;
document.getElementById("theOutput").innerHTML = globalArray.join(" | ");
stats = "The value " + dVal + " was inserted at element position " + Index + ".";
stats += "<BR><BR> There were " + numOfOps + " operations in this process.";
stats += "<BR><BR>This function represents an O(n) complexity algorithm.";
document.getElementById("theOutput2").innerHTML = stats;
numOfOps = 1;
// return varArray;
}
function SearchArray() {
sVal = document.getElementById("searchValue").value;
while(i < globalArray.length-1 && globalArray[i]!=sVal) {
numOfOps++;
i++;
}
...