如何理解快速排序算法

时间:2013-06-20 08:29:37

标签: java algorithm

根据我的材料,我正在学习java中的快速排序。最好的情况是枢轴是中位数,最坏的情况是枢轴的一侧总是空的。

对于以下代码,是“indexPartition”的支点吗?您在以下函数中放入了哪些参数,以便在最糟糕的情况下运行? < / p>

    private void quickSortSegment(E[] list, int start, int end)
{
  if (end-start>1) 
  { 
     int indexPartition = partition(list, start, end);
     quickSortSegment(list, start, indexPartition);
     quickSortSegment(list, indexPartition+1, end);
  }
}

private int partition(E[] list, int start, int end)
{
  E temp; 
  E partitionElement = list[start];
  int leftIndex = start; 
  int rightIndex = end-1;
  while (leftIndex<rightIndex)
  {  
    while (list[leftIndex].compareTo(partitionElement) <= 0 && leftIndex<rightIndex)
    {
        leftIndex++; 
    }
    while (list[rightIndex].compareTo(partitionElement) > 0)
    {
        rightIndex--; 
    }
     if (leftIndex<rightIndex)
     {  
        temp = list[leftIndex];
        list[leftIndex] = list[rightIndex];
        list[rightIndex] = temp;
     }
  }
  list[start] = list[rightIndex];
  list[rightIndex] = partitionElement;
  return rightIndex;
}

3 个答案:

答案 0 :(得分:1)

没有轴心partitionElement。似乎这段代码总是选择序列中的第一个元素作为枢轴。该函数将在所有情况下运行,包括最坏的情况,但它将表现不佳(具有方形复杂性)。

不同的人提出了选择枢轴的不同解决方案,但我个人喜欢这个:从考虑的区间中选择3个随机元素,计算它们的平均值并将其用作枢轴。

答案 1 :(得分:1)

Quick Sort Video

此视频与wikipedia文章一起应该清除。维基百科非常适合解释排序算法。关于您的问题,indexPartitionrightIndex,它是partitionElement的转轴。

答案 2 :(得分:1)

此方法partition()有问题,例如对于{3,1,2},我们将获得{1,3,2}:

public class CompareApp {
public static void main(String... args) {
    Integer[] arr = {3, 1, 2};
    quickSortSegment(arr, 0, 2);
    for (Integer i : arr) System.out.println(i);
}

private static <E extends Comparable> void quickSortSegment(E[] list, int start, int end) {
    if (end - start > 1) {
        int indexPartition = partition(list, start, end);
        quickSortSegment(list, start, indexPartition);
        quickSortSegment(list, indexPartition + 1, end);
    }
}


private static <E extends Comparable> int partition(E[] list, int start, int end) {
    E temp;
    E partitionElement = list[start];
    int leftIndex = start;
    int rightIndex = end - 1;
    while (leftIndex < rightIndex) {
        while (list[leftIndex].compareTo(partitionElement) <= 0 && leftIndex < rightIndex) {
            leftIndex++;
        }
        while (list[rightIndex].compareTo(partitionElement) > 0) {
            rightIndex--;
        }
        if (leftIndex < rightIndex) {
            temp = list[leftIndex];
            list[leftIndex] = list[rightIndex];
            list[rightIndex] = temp;
        }
    }
    list[start] = list[rightIndex];
    list[rightIndex] = partitionElement;
    return rightIndex;
}}
  

java system.compare.CompareApp

1 3 2