import java.util.arraylist;//array A, element 22 is not equal in ascending order. Please design an efficient algorithm to find out the a[i]=i data. Use two methods Public class binarysearch {public static void main (String[] args) { int[] nums={-1,1,2,3}; ArrayList<Integer> res=find (nums); for (int e:res) { system.out.println (e+ " "); } arraylist<integer> res2=binarysearch (nums); for (Int e:res2) { System.out.println (e+ " "); }}//method One public static arraylist<integer> find (int[] nums) {int n=nums.length; Arraylist<integer> all=new arraylist<integer> (); for (int i=0;i<n;i++) {if (nums[i]= =i) {All.add (nums[i]);} Else if (nums[i]>i) { break;}} Return all;} Method Two public static Arraylist<integer> binarysearch (int[] nums) {arraylist<integer> all=new Arraylist<integer> (); Int n=nums.length;if (n==0 | | nums[0]>0 | | nums[n-1]<n-1) {Return all;} At least one element has a value equal to its subscript int pivot=binaryfind (nums,0,n-1); All.add (pivot);//Find all target element for (int i=pivot-1;i>=) to the left 0 && i==nums[i];--i) {all.add (i);} Find all target elements to the right (int i=pivot+1;i<n && i==nums[i];i++) {all.add (i);} Return all;} Public static int binaryfind (int[] nums,int i,int j) { //binary search method int mid= (i+j)/2;if (nums[mid]==mid) {return mid;} Else if (Nums[mid]>mid) {return binaryfind (nums,i,mid-1);} Else{return binaryfind (NUMS,MID+1,J);}}}
This article is from the Apple blog, so be sure to keep this source http://59465168.blog.51cto.com/5268021/1965755
Java implements an ascending sort of shaped array A, element 22 is not equal to find a[i]=i data