常见算法之18---快速排序

快速排序基本思想
选定一个中枢元素,以其为基准点,将小于它的数放在其前面,大于其的数放在后面,把中枢元素放在最终合适的位置。然后再对左右两边分别递归。

 

快速排序的基本步骤:
1 初始时,以第一个元素作为中枢元素。低指针指向第一个元素,高指针指向最后一个元素。
2 当中枢元素在低指针时,从高指针开始向前查询第一个小于中枢元素的数,并交换这个数和中枢元素。将中枢元素移到高指针的位置。
3 当中枢元素在高指针时,处理方式同上相反。
4 当高低指针指向同一个位置时,说明完成一轮排序,此时中枢元素处在了最终的位置上。
5 之后,再对中枢元素两边进行相同操作。

 

基本代码:

public static void quickSort(int[] array, int start, int end) {
if (start < end) {
  //上述1
  int low = start;
  int high = end;
  int index = start;
  boolean highFlag = true;

  //上述4
  while (low < high) {
    //上述2
    if (highFlag) {

      while (array[index] <= array[high] && low < high) {

                         //low < high判断是有必要的,不加的话,也可能造成越界异常。
        high--;
      }

    int temp = array[index];
    array[index] = array[high];
    array[high] = temp;

    index = high;
    highFlag = false;
    }

    //上述3
    else {
      while (array[index] >= array[low] && low < high) {

        low++;
      }

      int temp = array[index];
      array[index] = array[low];
      array[low] = temp;

      index = low;
      highFlag = true;
     }
  }
  //上述5
  quickSort(array, start, low - 1);
  quickSort(array, low + 1, end);
  }
}

posted @ 2013-10-26 09:02  欧麦高德  阅读(187)  评论(0编辑  收藏  举报