//ARRAY PROBLEMS FOR COMS 161 – FRIDAY NOV 22nd 2019 //1(a) Display an array left-to-right list = new Array(10, 20, 40, 50, 65, 89, 93); i = 0; N = list.length; while (i < N) { alert(list[i]); i++; } //1(b) Display an array right-to-left?? i = list.length - 1; while (i >= 0) { alert(list[i]); i--; } //2(a) Find the average of the array elements i = 0; N = list.length; sum = 0; while (i < N) { //what to put here?? sum += list[i]; i++; } //what to put down here?? alert("average = " + (sum/N)); //2(b) Find the average AND the median of the array elements // The median is the middle number in a sorted array, // when there is just one middle number (i.e. when N is odd) // but it is the average of the 2 middle numbers when N is even. if (N % 2 == 1) alert("median = " + list[(N-1)/2]; else { med = (list[N/2] + list[N/2 - 1])/ 2; alert("median = " + med); } //3 The Binary Search Algorithm for N = 7: prez = new Array("Carter", "Clinton", "Eisenhower","Kennedy", "Nixon", "Obama", "Reagan"); year = new Array(1976, 1992, 1952, 1960, 1968, 2008, 1980); termLength = new Array(4, 8, 8, 3, 6, 8, 8); N = prez.length; desired = prompt("Enter last name of desired president: "); //Trace this mentally with Nixon first = 0; last = 6; found = false; while (first <= last && found == false) { mid = (first + last)/2; alert("first = " + first + " last = " + last + " mid = " + mid); if (desired > prez[mid]) first = mid + 1; else if (desired < prez[mid]) last = mid - 1; else found = true; } if (found == true) { alert(desired + " was elected in " + year[mid]); alert("He served " + termLength[mid] + " years as President"); alert("His term ran from " + year[mid] + " to " + (year[mid]+termLength[mid])); } else { alert("first = " + first + " last = " + last); alert("Could not find " + desired); }