码迷,mamicode.com
首页 > 编程语言 > 详细

快速排序

时间:2017-06-13 23:49:17      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:++   序列   ring   quicksort   star   start   array   UI   复杂   

1、算法思想:通过一趟排序将待排序记录分隔成独立的两部分,其中一部分的关键字均比另一部分的关键字小,则可分别对这两部分记录继续进行排序,从而达到排序目的。

2、代码实现:

public class QuickSort {
public static void main(String[] args) {

int[] array = {2, -5, 3, 1, 7, 4, 8, 6, 9};

QuickSort quickSort = new QuickSort();
int low = 0;
int high = array.length - 1;
quickSort.Sort(array, low, high);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] );
}
}

public void Sort(int[] arr, int from, int to) {

int start = from;
int end = to;
int key = arr[from];
while (end > start) {
//从后向前比较
//有比关键值小时交换
while ((arr[end] >= key) && (end > start)) {
end--;
}
//交换过程
if (arr[end] <= key) {
int temp = arr[end];
arr[end] = arr[start];
arr[start] = temp ;
}

//从前向后比较
while ((arr[start] <= key) && (end > start)) {
start++;
}
if (arr[start] >= key) {
int temp = arr[end];
arr[end] = arr[start];
arr[start] = temp;
}
}
//关键值左边序列
if (start > from) Sort(arr, from, start - 1);
//关键之右边序列
if (end < to) Sort(arr, end + 1, to);
}
}
注:另外还有优化的快速排序算法:1)采用随机选取方法选取关键值
                2)采用三数取中法,三个关键字取中间值,一般取左、右、中三个数,也可随机选取。
3、复杂度分析:1)最坏的情况是关键字为序列的端值是复杂度为O(log n)
        2)一般情况下为O(n log n)

快速排序

标签:++   序列   ring   quicksort   star   start   array   UI   复杂   

原文地址:http://www.cnblogs.com/chump-zwl/p/7003835.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!