二分查找+二分排序(快速排序)

来源:互联网 发布:华为windows平板 编辑:程序博客网 时间:2024/06/05 17:42
public class Main {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubint[] a = new int[]{3,2,5,1,6,8,2,4,1,0};quicksort(a, 0, a.length-1);for(int i=0;i<a.length;i++){System.out.print(a[i]+" ");}System.out.println("\n"+findVal(a,8));}static int findVal(int[] a,int val){int h = a.length-1;int l = 0;while(l<=h){//<=很重要int m = (h+l)/2;if(a[m]==val) return m;else if(a[m]>val)h = m-1;else l = m+1;}return -1;}static void quicksort(int[] a, int l, int h) {if(l < h) {int loc = sort(a, l, h);quicksort(a, l, loc - 1);quicksort(a, loc + 1, h);}}static int sort(int[] a, int l, int h) {int temp = a[l];while(l<h){while(l<h&&temp<a[h]) h--;a[l]=a[h];while(l<h&&a[l]<=temp) l++;//<=很重要,当有数据重复时a[h]=a[l];}a[l]=temp;return l;}}
0 1 1 2 2 3 4 5 6 8 9

0 0
原创粉丝点击