您的位置:首页 > 产品设计 > UI/UE

快速排序(Quick-Sort)

2017-11-02 22:22 316 查看

快速排序(Quick-Sort)

对于包含n个数的数组来说,快速排序是一种最坏情况下时间复杂度为O(n²)的排序算法。虽然最坏情况下的时间复杂度很差,但是快速排序通常是实际应用中最好的选择,因为它的平均性能非常好

下面是算法导论中给出的快速排序的伪代码:

QUICK-SORT(A,p,r)

  if p < r

  q = PARTITION(A,p,r)

  QUICK-SORT(A,p,q - 1)

  QUICK-SORT(A,q + 1,r)

PARTITION(A,p,r)

  x = A[r]

  i = p - 1

  for j = p to r - 1

    if A[j] <= x

      i = i + 1

      exchange A[i] with A[j]

  exchange A[i + 1] with A[r]

  return i + 1

下面是快速排序的Java实现:

/**
* Created by CvShrimp on 2017/10/12.
*/
public class QuickSort {
public static int partition(int[] array, int p, int r) {
int i = p - 1;
for(int j = p; j < r; j++) {
if(array[j] <= array[r]) {
i++;
swapArrayElement(array, i, j);
}
}
i++;
swapArrayElement(array, i, r);
return i;
}

public static void quickSort(int[] array, int p, int r) {
if(p < r) {
int q = partition(array, p, r);
quickSort(array, p, q - 1);
quickSort(array, p + 1, r);
}
}

public static void swapArrayElement(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}

public static void main(String[] args) {
int[] array = {1,6,10,5,666,4,66,666};
QuickSort.quickSort(array, 0, array.length - 1);
System.out.print("Sorted result: ");
for(int temp : array) {
System.out.print(temp + " ");
}
System.out.println();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息