Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

//this method allows you to non-recursively perform binary search on an array in

ID: 3649981 • Letter: #

Question

//this method allows you to non-recursively perform binary search on an array in ascending //order
public static int BinarySearch_nr(int[] arr, int start, int end, int key)
{
//your implementation of this method goes here
}

MAIN METHOD HERE:
public static void main(String[] args){

int[] a = new int[10];
a[0] =0;
a[1] =220;
a[2] =10;
a[3] =50;
a[4] =20;
a[5] =70;
a[6] =60;
a[7] =50;
a[8] =90;
a[9] =30;

int key = 6;
System.out.println("Binary Search: the position of "+key+" is "+ BinarySearch_nr(a,0,9,key));
}

Explanation / Answer

please rate - thanks

  
   import java.util.*;
    public class binarysearch
{   //this method alstarts you to non-recursively perform binary search on an array in ascending //order
public static int BinarySearch_nr(int[] arr, int start, int end, int key)
{
//your implementation of this method goes here
int mid,t;
//array must be sorted
for(int i=0;i<end-1;i++)
      for(int j=i+1;j<end;j++)
            if(arr[i]>arr[j])
                  {t=arr[i];
                    arr[i]=arr[j];
                    arr[j]=t;
                    }
while( start <= end )
        {mid = ( start + end ) / 2;
        //System.out.println(arr[mid]+" "+key+" "+mid);
             if( arr[ mid ]<key )
                   start = mid + 1;
                else
                {if( arr[ mid ]>key )
                  end = mid - 1;
               else
                   return mid;
                    }
          }

        return -1;
    }
   



public static void main(String[] args){

int[] a = new int[10];
a[0] =0;
a[1] =220;
a[2] =10;
a[3] =50;
a[4] =20;
a[5] =70;
a[6] =60;
a[7] =50;
a[8] =90;
a[9] =30;

int key = 6;
System.out.println("Binary Search: the position of "+key+" is "+ BinarySearch_nr(a,0,9,key));
}
}