You will write a function with 3 arguments. The name of the function will be InsertIntoArray. Argument 1 is the array, argument 2 is the index of where you are going to insert a new number, argument 3 is the number to insert. The program should insert the new number at the index given and shift all the previous entries index up by 1. Since the array is capped at 1000, the highest element of the array will be deleted. Count the number of operations performed on the array and output this to the screen. An operation is if you assign a value or compare a value - only compare or assign operations should be counted.
Big O Notation
<br/>Algorithm is O(N)
<br/> Index:
<input type="textbox" id="index" value="2" />
<br/> Value:
<input type="textbox" id="value" value="2" />
<br/>
<input type="button" value="Create Array" onClick="createArray();" />
<input type="button" value="Insert Into Array" onClick="insertIntoArray();" />
<div id="output2"></div>
<div id="output"></div>
<br/>
JavaScript
var size = 1000;
var array = new Array(size);
var globalCounter = 0;
var d = " ";
//creates array of random values
function createArray() {
clearDisplay();
for (var i = 0; i < size; i++) {
array[i] = Math.floor(Math.random() * (size))
//counts steps
globalCounter++
}
displayArray();
out = "Total Operations = " + globalCounter;
document.getElementById("output2").innerHTML = out;
}
function clearDisplay() {
d = " ";
document.getElementById("output").innerHTML = "";
}
//creates array leanth
function displayArray() {
for (var i = 0; i < size; i++) {
d += i + " : " + array[i] + "<br/>"
}
document.getElementById("output").innerHTML = d;
}
function insertIntoArray() {
clearDisplay();
//gets string value from HTML and converts to integer for index and value
var index = parseInt(document.getElementById("index").value);
var value = parseInt(document.getElementById("value").value);
//prints to screen
d = "Inserting " + value + " at " + index + "<br/>";
//for loop determining where to insert based on input values
for (var a = size - 1; a >= (index + 1); a--) {
array[a] = array[a - 1];
globalCounter++;
}
array[index] = value;
globalCounter++
displayArray();
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.