选择法排序数组+折半查找判断输入的数是否在数组中
package com.shu; import java.util.*; public class example2_5 { public static void main(String[] args) { int start=0,end,middle; int a[] = {23,120,34,3,78,90,12,236}; int N = a.length; //选择法排序数组 for(int i=0;i<N;i++){ for(int j=i+1;j<N;j++){ if(a[j]<a[i]){ int t = a[j]; a[j] = a[i]; a[i] = t; } } } Scanner reader = new Scanner(System.in); System.out.println("输入整数,通过程序判断该整数是否在数组中"); int number = reader.nextInt(); int count = 0; end = N; middle = (start+end)/2; //折半查找 while(number!=a[middle]){ if(number>a[middle]){ start = middle; }else if(number<a[middle]){ end = middle; } middle = (start+end)/2; count++; if(count>N/2){break;} } if(count>N/2){ System.out.printf("%d不在数组中",number); }else{ System.out.printf("%d在数组中",number); } } }