Assignment 2(scratch)
by Ebony McCoy
HTML
Array Size <input type="textbox" size="4" id="_size" value="100">
<button onclick="document.getElementById('output1').innerHTML= getArray();">Create Array</button>
<br>
<br>
Enter Index<input type="textbox" size="4" id="_index">Value to Insert<input type="textbox" size="4" id="_content">
<button onclick=InsertIntoArray();> Insert Into Array</button>
<br>
<br>
Enter Value to Find<input type="textbox" size="4" id="_search">
<button onclick=searchArray();>Search Array</button>
<p id='output1'></p>
<p id='output2'></p>
<p id='output3'></p>
<p id='output4'></p>
<p id='output5'></p>
<p id='output6'></p>
CSS
body{
background-color: Dodgerblue;
}
JavaScript
var array = [];
function getArray(){
clearDisplay();
var length= document.getElementById("_size").value;
for(var i = 0; i < length; i++){
array[i]= Math.floor((Math.random()*100)+1);
}
return array;
}
function InsertIntoArray(){
var index = document.getElementById("_index").value;
var number = document.getElementById("_content").value;
var length = document.getElementById("_size").value;
var opt = 0;
for(i = length - 1; i >= index; i-- ){
if(i > index){
array[i] = array[i-1];
opt++;
}
else if(i == index){
array[i]= number;
opt++;
}
}
document.getElementById('output1').innerHTML = array;
document.getElementById('output2').innerHTML = number + " was entered at index " + index + ".";
document.getElementById('output3').innerHTML = "There were " + opt + " operations performed in this insertion. The time complexity is O:" + opt + ").";
}
clearDisplay();
function clearDisplay() {
reset = "";
document.getElementById("output1").innerHTML = "";
}
function searchArray(){
var opt = 0;
var search = document.getElementById("_search").value;
var firstIndex = array.indexOf(search);
for(var i = 0; i < array.length; i++){
opt++;
if(array[i] == search){
firstIndex = i;
break;
}
}
if(firstIndex != null){
document.getElementById('output4').innerHTML = "The first instance of " + search + " was found at index " + firstIndex + ".";
document.getElementById('output5').innerHTML = "There were " + opt + " operations performed in this search. The time complexity is O: " + opt + ").";
}else{
document.getElementById('output6').innerHTML = "The number " + search + " was not found. There were " + opt + " operations performed in this insertion. The time complexity is O: " + opt + ").";
}
}