快速排序

来源:互联网 发布:碑文 软件 编辑:程序博客网 时间:2024/05/22 06:55

快速排序

步骤:
- 首先设定一个分界值,通过该分界值将数组分成左右两部分。
- 将大于等于分界值的数据集中到数组右边,小于分界值的数据集中到数组的左边。此时,左边部分中各元素都小于等于分界值,而右边部分中各元素都大于等于分界值。
- 然后,左边和右边的数据可以独立排序。对于左侧的数组数据,又可以取一个分界值,将该部分数据分成左右两部分,同样将左边放置较小值,右边放置较大值。右侧的数组数据也可以做类似处理。
- 重复上述过程,可以看出,这是一个递归定义。通过递归将左侧部分排好序后,再递归排好右侧部分的顺序。当左、右两部分各数据排序完成后,整个数组的排序也就完成了。

代码:

public class P4_5 {    static final int SIZE = 18;    public static void quickSort(int[] arr,int left,int right){       int f,t;       int rtemp,ltemp;       ltemp = left;       rtemp = right;       f = arr[(left+right)/2];  // 分界值       while (ltemp<rtemp){           while (arr[ltemp]<f){               ++ltemp;           }           while (arr[rtemp]>f) {               --rtemp;           }           if(ltemp<=rtemp){               t=arr[ltemp];               arr[ltemp] = arr[rtemp];               arr[rtemp] = t;               --rtemp;               ++ltemp;           }       }       if (ltemp==rtemp){           ltemp++;       }       if(left<rtemp){           quickSort(arr,left,ltemp-1);       }       if(ltemp<right){           quickSort(arr,rtemp+1,right);       }    }    public static void main(String[] args) {        int[] shuzu = new int[SIZE];        for (int i = 0; i < SIZE; i++) {            shuzu[i] = (int)(100 + Math.random()*(100+1));        }        //        System.out.println("排序前数组为:");        for (int i = 0; i < shuzu.length; i++) {            System.out.print("  "+ shuzu[i]);        }        //        System.out.println();        quickSort(shuzu,0,SIZE-1);        System.out.println("排序后数组为:");        for (int i = 0; i < shuzu.length; i++) {            System.out.print("  "+ shuzu[i]);        }    }}

运行结果:

排序前数组为:  122  186  127  146  123  110  196  165  175  146  170  134  177  121  100  170  161  100排序后数组为:  100  100  110  121  122  123  127  134  146  146  161  165  170  170  175  177  186  196Process finished with exit code 0
原创粉丝点击