package BinarySerach;
import java.util.Scanner;
public class BinarySerch {
/**
*折半查找和快速排序
*/
static final int N = 15;
static void quickSort(int [] array,int left,int right){
int f,t;
int ltemp =left;
int rtemp = right;
//确定分界值
f = array[(left+right)/2];
while(ltemp < rtemp){
while(array[ltemp] <f){
++ltemp;
}
while(array[rtemp] > f){
--rtemp;
}
if(ltemp <= rtemp){
t = array[ltemp];
array[ltemp] = array[rtemp];
array[rtemp] = t;
--rtemp;
++ltemp;
}
if(ltemp == rtemp){
ltemp++;
}
if(left < rtemp){
quickSort(array, left, ltemp-1);
}
if(ltemp < right){
quickSort(array, rtemp+1, right);
}
}
}
//折半查找
static int searchFun(int a[],int n,int x){
int mid,low,high;
low = 0;
high = n-1;
while(low <= high){
mid = (low+high)/2;
if(a[mid] == x){
return mid;
}else if(a[mid] > x){
high = mid -1;
}else{
low = mid+1;
}
}
return -1;
}
public static void main(String[] args) {
int [] shuzu = new int[N];
int x,n,i;
for(i=0;i<N;i++){
shuzu[i] = (int)(100+Math.random()*(100+1));
}
for(i=0;i<N;i++){
System.out.print(" "+shuzu[i]);
}
System.out.println("輸出排序的結果:");
quickSort(shuzu, 0, N-1);
for(i=0;i<N;i++){
System.out.print(" "+shuzu[i]);
}
System.out.println();
System.out.println("輸入要查找的數字");
Scanner input = new Scanner(System.in);
x = input.nextInt();
n = searchFun(shuzu, N, x);
System.out.println(n);
if(n < 0){
System.out.println("沒有找到");
}else{
System.out.println("資料:"+x+"位于數組中的第"+(n+1)+"個元素處。");
}
}
}
轉載于:https://www.cnblogs.com/aicpcode/p/4271366.html