Insert_Array
Create and insert an array
by scotp71
HTML
Enter Array Size:
<input type="textbox" id="tbArraySize" value = "10" />
<br/>
<input type="button" id=btnCreate value="Create Array" onClick="createArray();" />
<br/>
Enter Location:
<input type="textbox" id="tbInsertIndex" value = "2"/>
<br/>
Enter Value to Insert:
<input type="textbox" id="tbInsertValue" value="10" />
<br/>
<input type="button" id=btnInsert value="Insert into Array" onClick="insertIntoArray();" />
<br/>
Enter a Value to Find:
<input type="textbox" id="tbSearchValue" value="20" />
<br/>
<input type="button" id=btnSearch value="SearchArray" onClick="searchArray();" />
<br/>
<div id="output">
</div>
JavaScript
var array = []; // Flobal array to hold array
var d = ""; // Global string for output
var count = 0;
function createArray() {
clearDisplay();
var size=parseInt(document.getElementById("tbArraySize").value);
array = new Array(size);
for (var i = 0; i<=size; i++) {
array[i] = Math.floor(Math.random()*100) + 1;
}
displayArray();
}
function clearDisplay()
{
//Global string d is used to hold display
d = "";
// The div element named output is used to display output
document.getElementById("output").innerHTML = "";
}
function displayArray()
{
// simple loop to add array values to string d
for (var i = 0; i < array.length - 1; i++) {
d += i + ' : ' + array[i] + "<br/>";
}
document.getElementById("output").innerHTML = d;
}
function insertIntoArray(array, index, num) {
// get value of index of value to insert
var n = parseInt(document.getElementById("tbInsertIndex").value);
// get actual value to insert at index i
var v = parseInt(document.getElementById("tbInsertValue").value);
//var length = array.length;
var size=parseInt(document.getElementById("tbArraySize").value);
d = "Value " + v + " inserted at location " + n + ".<br/>" + "There are " + count + "<br/>";
for (i = size - 1; i > n; i--) {
count++;
array[i] = array[i - 1];
}
array[n] = v; {
count++;
} {
displayArray();
}
}
function searchArray() {
clearDisplay();
var s = parseInt(document.getElementById("tbSearchValue").value);
var size=parseInt(document.getElementById("tbArraySize").value);
var vcounter=0;
for (var i = 0; i<size; i++) {
count++;
if (array[i]==s) {
vcounter++;
d = "Your value, " + s + " was found at " + i + " location";
}
if (vcounter==0) {
d = "Your value " + s + " was not found. There were " + count + " operations performed.";
}
}
displayArray();
}