import java.util.Scanner; public class z6 { public static int count=0; public void sort(int arr[],int left,int right){ if(left>=right){ return; } else{ int i=left,j=right; int key=arr[left]; while (i<j){ while (j>i&&arr[j]>=key){ j--; } while (i<j&&arr[i]<=key){ i++; } if(i<j){ int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } arr[left]=arr[i]; arr[i]=key; sort(arr,left,i-1); sort(arr,j+1,right); } } public int search(int arr[],int key,int low,int high){ int middle; int n=1; if (key<arr[low]||low>high||key>arr[high]){ return -1; }else { count=0; middle = (low + high) / 2; if (key < arr[middle]) { return search(arr, key, low, middle - 1); } else if (arr[middle] < key) { return search(arr, key, middle + 1, high); } else { do { //System.out.println(middle); count++; //System.out.println(count); //System.out.println(arr[middle]); // System.out.println(arr[middle+1]); }while (arr[middle]==arr[middle+count]); for (int i = 0; i <n; i++) { if(arr[middle]==arr[middle-n]){ n++; middle--; count=count+n-1; } } return middle; } } } public static void main(String []args){ int arr[]=new int[]{1,6,5,-5,9,5,14,2,-2,0,12,6,8,-3,6,9,13,-12}; System.out.println("原数组为:"); for (int m:arr ) { System.out.print(m+" " ); } System.out.println(""); z6 z6=new z6(); z6.sort(arr,0,arr.length-1); System.out.println("快速排序完毕,数组从小到大为:"); for (int m:arr ) { System.out.print(m+" " ); } Scanner Sc = new Scanner(System.in); System.out.println(""); System.out.println(""); while (true) { System.out.println("您要搜索哪个数字!"); int number = Sc.nextInt(); int result = z6.search(arr, number, 0, arr.length - 1); System.out.println("二分查找检索完毕!"); if (result == -1) { System.out.println("您要查找数字:" + number + ",对不起,未检测到此数字!"); } else { System.out.println("您要查找数字:" + number + ",数组中含有此数"+(count)+"个,"); if(count==1){ System.out.println("他是"+"arr["+result+"]"); } // System.out.println("15是"+arr[15]); if (count>1){ System.out.println("他们是"); count=1; while (arr[result]==arr[result+count]){ count++; } System.out.println(count); for (int i = 0; i <count; i++) { System.out.print("arr["+(result+i)+"] "); } System.out.println(""); } } } } }
java实现 快排+二分查找
猜你喜欢
转载自blog.csdn.net/qq_37455615/article/details/82823680
今日推荐
周排行