字符二分快速查找
import java.util.Scanner; /** * * @author luozhonghua * */ public class charSearchAndSort { static void kuaiSu(char[] a,int left,int right) //字符快速排序 { int f,l,r; char t; l=left; r=right; f=a[(left+right)/2]; while(l<r){ while(a[l]<f) ++l; while(a[r]>f) --r; if(l<=r){ t=a[l]; a[l]=a[r]; a[r]=t; ++l; --r; } } if(l==r) l++; if(left<r) kuaiSu(a,left,l-1); //递归调用 if(l<right) kuaiSu(a,r+1,right); //递归调用 } static int searchFun(char []a,int n,char 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) { char[] str=new char[80]; int N; char[] x=new char[80]; System.out.print("输入一个字符串:"); Scanner input=new Scanner(System.in); str=input.next().toCharArray(); //输入字符串 N=str.length; System.out.print("排序前:\n"); System.out.println(str); //输出 kuaiSu(str,0,N-1); //二分排序 System.out.print("排序后:\n"); System.out.print(str); //输出 //二分查找 System.out.print("\n"); System.out.println("输入要查找的字符:"); Scanner inpu=new Scanner(System.in); x=inpu.next().toCharArray(); //输入要查找的数 int n=searchFun(str,N,x[0]); //查找 if(n<0) //输出查找结果 System.out.println("没找到数据:"+x); else System.out.println("数据:"+x[0]+" 位于数组的第"+(n+1)+" 个元素处。"); } }
地瓜园