快速排序【JAVA实现】

来源:互联网 发布:市场营销大数据分析 编辑:程序博客网 时间:2024/06/10 13:39

/* * 1、先选定并记住主元,start指向左边第一个元素,end指向右边第一个元素; * 2、则从最右边第一个元素(end)开始判断,如果比主元大,则end--,反之则将end指的元素赋值给start指的元素,并且start++; * 3、然后从左边(start)开始判断,如果比主元小,则start++,反之则将start指的元素赋值给end指的元素,并且end--; * 4、一直重复2,3两步,直到条件start<end不再满足为止;这时就可以把主元赋值给start指的元素; * 5、这时就完成了主元左右两个子集的划分,然后可以对左右两个子集进行递归操作,完成排序; */public static void solve2(int[] array,int start,int end){int len = end-start+1;if (len <= 1)         return; int main = start;    int value = array[main];     while (start < end) {         for (; start < end; --end) {             if (array[end] < value) {             array[start++] = array[end];                 break;             }         }         for (; start < end; ++start) {             if (array[start] > value)            {            array[end--] = array[start];                break;            }        }    }    array[start] = value;    solve2(array, 0,start-1 );    solve2(array,start+1,len-1);}

测试:


public static void main(String[] args) {      int[] a = {12,15,1,18,2,35,30,11};        System.out.print("排序之前: ");        display(a);        solve2(a, 0, a.length-1);        System.out.print("排序之后: ");      display(a);}

结果:

排序之前: 12 15 1 18 2 35 30 11 排序之后: 1 2 11 12 15 18 30 35 


0 0
原创粉丝点击