剑指offer——快速排序

来源:互联网 发布:mac显示flash版本过低 编辑:程序博客网 时间:2024/04/25 17:08

        快速排序是目前所有排序中性能较好的一种算法,最好情况和平均情况下时间复杂度均为O(nlogn),最坏的情况下时间复杂度为O(n^2)。快速排序采用递归,用空间换取时间。由于使用了递归,因此需要额外的存储空间。

        快速排序由三个函数构成,分别为QuickSort(int[] arr)、QuickSort(int[] arr,int start,int end)、partition(int[] arr,int start,int end)。其中partition函数能够从当前待排序序列中找出一个主元,并使得主元左侧的元素均小于主元,主元右侧的元素均大于主元。Partition函数完成对待排序序列的分割后,交给QuickSort(int[] arr,int start,int end)处理,QuickSort分别将被Partition分隔的两个子序列进行快速排序。QuickSort(int[] arr)是整个快速排序的入口函数,用户只需传入待排序数组即可。

        下面为java实现的快速排序,若有bug欢迎拍版

/** * 实现快速排序  * @author chibozhou */public class QuickSort {/** * 本函数实现一趟快速排序,以数组的第一个元素为主元, * 本函数运行结束后使得主元左侧的元素小于主元,主元右侧的元素大于主元。 * @param arr 待排序的数组 * @return 返回经一趟排序后主元的下标 */private static int partition(int[] arr,int start,int end){//健壮性判断if(arr.length<=0){System.out.println("数组为空!");return -1;}if(start<0 || end<0 || start>end){System.out.println("start、end非法!");return -1;}//i指向数组头、j指向数组尾int i=start+1,j=end;//选择数组第一位为主元int key = arr[start];//若i与j未相遇,则执行以下循环while(i<j){//i从左向右扫描,直到当前元素大于主元时停下while(arr[i]<=key && i<end){i++;}//j从右向左扫描,直到当前元素小于主元时停下while(arr[j]>=key && j>start){j--;}//i、j停下有两种情况:1.if(i<j)swap(arr,i,j);}//将主元与j交换swap(arr,start,j);System.out.println("某一趟排序结果:"+printArray(arr));//返回新的主元下标return j;}/** * 快速排序入口函数 * @param arr 待排序数组 * @return 返回有序的数组 */public static void QuickSort(int[] arr){//健壮性判断if(arr==null || arr.length<=0){System.out.println("数组为空!");return;}//通过递归进行快速排序QuickSort(arr,0,arr.length-1);}/** * 快速排序的递归函数 * @param arr 待排序数组 * @param start 数组的起始下标 * @param end 数组的结束下标 * @return 返回当前有序子序列 */private static void QuickSort(int[] arr,int start,int end){if(start<end){//获取主元int key = partition(arr,start,end);//对主元左侧的序列进行快速排序QuickSort(arr,start,key-1);//对主元右侧的序列进行快速排序QuickSort(arr,key+1,end);}}/** * 实现i与j位置的元素交换 * @param arr 数组 * @param i 下标 * @param j 下标 */private static void swap(int[] arr,int i,int j){//健壮性判断if(arr==null || arr.length<=0){System.out.println("数组为空!");return;}//定义临时变量temp实现交换int temp = arr[i];arr[i] = arr[j];arr[j] = temp;}/** * 输出数组元素 * @param arr * @return */private static String printArray(int[] arr){if(arr==null){System.out.println("数组为空!");return null;}StringBuffer sb = new StringBuffer();for(int i=0;i<arr.length;i++){sb.append(arr[i]);}return sb.toString();}}


1 0
原创粉丝点击