Question: How would I write the insertion sort algorithm to work with the rest of the code instead of the sort function on this piece of

How would I write the insertion sort algorithm to work with the rest of the code instead of the sort function on this piece of javascript. var list =[];
var sortedList =[];
function populateList(){
list =[];
for (let i =0; i <20; i++){
list.push(randomString());
}
displayList(list, 'listSection');
}
function randomString(){
return Math.random().toString(36).substring(2,10);
}
function displayList(arr, elementId){
document.getElementById(elementId).textContent = arr.join(',');
}
function sortList(){
sortedList =[...list];
sortedList.sort();
displayList(sortedList, 'sortedListSection');
}
// Insertion Sort implementation
function insertionSort(inputArr){
var n = inputArr.length;
for (let i =1; i < n; i++){
// Choosing the first element in our unsorted subarray
var current = inputArr[i];
// The last element of our sorted subarray
var j = i -1;
while (j >=0 && current < inputArr[j]){
inputArr[j +1]= inputArr[j];
j--;
}
inputArr[j +1]= current;
}
return inputArr;
}
function insertValue(){
var value = document.getElementById('insertValue').value;
if (value.trim()===''){
alert('Please enter a value.');
return;
}
sortedList.push(value);
sortedList.sort();
displayList(sortedList, 'sortedListSection');
}
function randomizeList(){
populateList();
document.getElementById('sortedListSection').textContent ='';
}
populateList();

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!