Find number in array
Problem : Write a method that takes a sorted array A of integers and a key k
return the index of first occurrence of k h A return -l if k does Rot
appear in A. Write tests to verify your code.
what is best case scenario is your key index 0 and worst case is last element which takes o(n) within large array even sorted it takes time to find index in array size 2^10
Let's figure out using binary search
package Search; /** * Write a method that takes a sorted array A of integers and a key k md retums the hdex of first occurrmce of k h A Retum -l if k does Rot appear in A. Write tests to verify your code. * @author Mohamed fawzy * @copyright GPL */ public class BinarySearch { public static int search(int a[], int k){ int low=0; int high= a.length-1; int middle; while(low <= high){ middle = low + (high - low) /2; if(a[middle]==k){ return middle; }else if(a[middle] < k){ low = middle+1; }else{ high = middle-1; } } return -1; } }
Test case :
package Search; public class BinarySearchTest { public static void main(String[] args){ int[] array = {1,2,3,4,6,10,15,20}; int k = 10; BinarySearch binarysearch = new BinarySearch(); int index = binarysearch.search(array, k); System.out.println(index); } }
Comments
Post a Comment