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

Algorithm backup ---- Quick Sort(快速排序算法)

2009-11-03 13:26 405 查看
  The quick sort is an in-place, divide-and-conquer, massively recursive sort. Typically, quicksort is significantly faster in practice than other Θ(nlogn) algorithms, because its inner loop can be efficiently implemented on most architectures, and in most real-world data, it is possible to make design choices which minimize the probability of requiring quadratic time.

  The recursive algorithm consists of four steps (which closely resemble the merge sort):

1. If there are one or less elements in the array to be sorted, return immediately.

2. Pick an element, called a pivot, from the list.

3. Reorder the list so that all elements which are less than the pivot come before the pivot and so that all elements greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.

4. Recursively sort the sub-list of lesser elements and the sub-list of greater elements.

  The efficiency of the algorithm is majorly impacted by which element is choosen as the pivot point. The worst-case efficiency of the quick sort, O(n2), occurs when the list is sorted and the left-most element is chosen. Randomly choosing a pivot point rather than using the left-most element is recommended if the data to be sorted isn't random. As long as the pivot point is chosen randomly, the quick sort has an algorithmic complexity of O(n log n).

  Pros: Extremely fast.
  Cons: Very complex algorithm, massively recursive.

  Below is the basic quick sort algorithm:

/// <summary>
/// Quick sort algorithm
/// </summary>
/// <param name="numbers">numbers array to be sorted</param>
/// <param name="left">start subscript</param>
/// <param name="right">end subscript</param>
public static void QuickSort(int[] numbers, int left, int right)
{
if (left < right)
{
int key = numbers[left];
int i = left;
int j = right;
while (i < j)
{
//Find the element which <= key starting from end
while (i < j && numbers[j] > key) j--;
if (i < j)
{
numbers[i] = numbers[j];
i++;
}
//Find the element which >= key starting from beginning
while (i < j && numbers[i] < key) i++;
if (i < j)
{
numbers[j] = numbers[i];
j--;
}
numbers[i] = key;
}

QuickSort(numbers, left, i - 1);
QuickSort(numbers, i + 1, right);
}
}

Go to my home page for more posts
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: