nie-ii-year

lab stuff from undergrad second year.
git clone http://git.hanabi.in/repos/nie-ii-year.git
Log | Files | Refs | LICENSE

recursive.js (856B)


      1 function binarySearch(key, arr, low = 0, high = arr.length - 1){
      2   if(low > high)
      3     return -1;
      4   mid = (low + high) >> 1;
      5   if(arr[mid] == key)
      6     return mid;
      7   if(arr[mid] < key)
      8     return binarySearch(key, arr, mid + 1, high);
      9   else
     10     return binarySearch(key, arr, low, mid - 1);
     11 }
     12 
     13 var size;
     14 do{
     15   print("Enter array size: ");
     16   size = readline();
     17   size = parseInt(size);
     18   if(size % 1 !== 0 || size < 1)
     19     print("Invalid size, try again.");
     20 }while (size % 1 !== 0 || size < 1);
     21 
     22 array = [];
     23 array.length = size;
     24 print("Enter array elements: ");
     25 
     26 for(var i = 0; i < size; i++)
     27   array[i] = readline();
     28 
     29 array.sort(function(a, b){return a - b;});
     30 
     31 print("Enter key to be searched: ");
     32 key = readline();
     33 
     34 location = binarySearch(key, array);
     35 
     36 if(location > -1)
     37   print(key + " was found at: " + location);
     38 else
     39   print(key + " was not found.");