class binarySearch{ public static void main(String[] arg) { int n=10; int arr[]={1,2,3,4,5,6,7,8,9,10}; int key=8; int start=0; int end=n-1; int mid; if(arr[0]>arr[1]) { System.out.println("Descending "); while(start<end) { mid=(start+end)/2; if(arr[mid]==key) { System.out.println(/*"Element is " + key*/ " which present at index " + mid ); break; } else if(arr[mid]<key) { start=mid+1; } else if(arr[mid]>key) { end=mid-1; } } } else if(arr[0]<arr[1]) { System.out.println("Ascending"); while(start<end) { mid=(start+end)/2; if(arr[mid]==key) { System.out.println(/*"Element is " + key*/ " which present at index " + mid ); break; } else if(arr[mid]>key) { start=mid+1; } else if(arr[mid]<key) { end=mid-1; } } } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter