折半查找链接:https://baike.baidu.com/item/%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE/10628618?fromtitle=%E6%8A%98%E5%8D%8A%E6%9F%A5%E6%89%BE&fromid=9796273&fr=aladdin
快速排序链接:https://baike.baidu.com/item/%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95?fromtitle=%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F&fromid=2084344
1 package Mypackage;
2
3 import java.util.*;
4
5 public class 折半查找_快速排序 {
6 //快速排序
7 static int a[]=new int[100];
8 static int n=0;
9 static int num=0;
10
11 static void quicksort(int left,int right)
12 {
13 int temp=0;
14 int i=0;
15 int j=0;
16 int t=0;
17 if(left>right)
18 return;
19 temp=a[left];
20 i=left;
21 j=right;
22 while(i!=j)
23 {
24 while(i<j && a[j]>=temp)
25 j--;
26 while(i<j && a[i]<=temp)
27 i++;
28 //两个数的交换
29 if(i<j)
30 {
31 t=a[j];
32 a[j]=a[i];
33 a[i]=t;
34
35 }
36 }
37 //基准数归位
38 a[left]=a[i];
39 a[i]=temp;
40
41 quicksort(left,i-1);
42 quicksort(i+1,right);
43
44 return;
45 }
46
47 //折半查找
48 static int BinarySearch(int start, int end,int num)
49 {
50 int mid=0;
51 while(start<=end)
52 {
53 mid=(start+end)/2;
54 if(num==a[mid]) {
55 return mid;//返回到下标
56 }
57 else if(num>a[mid])
58 {
59 start=mid+1;
60 }
61 else {
62 end=mid-1;
63 }
64 }
65
66 return -1;
67 }
68 public static void main(String[] args) {
69 int start=1;
70 int end=0;
71 int i=0;
72 Scanner reader=new Scanner(System.in);
73 System.out.print("输入数组的长度为:");
74 n=reader.nextInt();
75 end=n;
76 for(i=1;i<=n;i++)
77 {
78 a[i]=reader.nextInt();
79 }
80
81 quicksort(1,n);
82 System.out.println("排序后的数组为:");
83 for(i=1;i<=n;i++)
84 {
85 System.out.print(+a[i]+" ");
86 }
87 System.out.println("
");
88 System.out.println("请你输入你查找的值:");
89 num=reader.nextInt();
90 int value=BinarySearch(start,end,num);
91 if(value!=-1)
92 System.out.println("其索引值:"+value);
93 else
94 System.out.println("the value not exist");
95 }
96 }