Problem 3 In this problem, develop an algorithm to search a key in a sorted array. Given an input array of integers and
-
- Site Admin
- Posts: 899603
- Joined: Mon Aug 02, 2021 8:13 am
Problem 3 In this problem, develop an algorithm to search a key in a sorted array. Given an input array of integers and
Develop flowchart for this algorithm o Give pre-condition and post-condition for your algorithm. O O The algorithm takes as input a search key and an array, output "key in arr: YES" or "key in arr: NO" Hint: use loop and two variables, one to store the starting index of the current search subarray and another to store the end of the current search subarray. These variables are often called start, end, low, high, etc. Let's call it L and H. In each iteration we search array from index L to H. Initially L is 0 and H is the last index of the original array. In each iteration of the loop, we get middle index M and middle value. If the search key is smaller than the middle values, search 1st half of the array by setting H to be M-1 (L does not change), otherwise, search the 2nd half by setting L to be M+1 (H does not change). Convince yourself this works correctly. o If the search (sub)array is of even size, the middle index can be either the end of the 1st half or the beginning of the 2nd half (so to be precise, the "middle" element should be called "middle-most" element). . The loop should stop immediately when the key is found. What is the terminating condition of the search loop? Must use loops. You should not use recursions. (We will learn recursion later). o Start your flowchart as shown in the following figure. The algorithm takes as input an array arr and a search key key Save the flowchart as img_search.jpg OOO O start arr[] key Implement the algorithm using JavaScript o Complete the function problem3(), and attach the onclick event to the corresponding button in html.. O Your implementation should match your flowchart. Sample output
49.8 102 103 104 105 function problem3() { 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 var arr=[8, 9, 9, 12, 13, 13, 13, 15, 20, 100, 100, 101, 123, 129, 300, 330, 390, 400, 403, 407]; var r= prompt("enter search key for..."); /* you implementation here */ /* prompt user for key with message "enter search key for .. var L = 0; var H= arr.length - 1; while (L <= H) { } let M = Math.floor((L+H)/2); if (arr[M] == key) 3 r = M; H= M-1; B else if(key < arr[M]) H = M = 1; else L = M + 1; see pdf / document.getElementById("output").innerHTML + "in arr:" + (key? 'yes': 'No');