quicksort算法
One of the common problems in programming is to sort an array of values in some order (ascending or descending).
编程中的常见问题之一是按某种顺序(升序或降序) 对值数组进行排序。
While there are many "standard" sorting algorithms, QuickSort is one of the fastest. Quicksort sorts by employing a divide and conquer strategy to divide a list into two sub-lists.
尽管有许多“标准”排序算法,但QuickSort是最快的算法之一。 Quicksort通过采用分而治之策略将一个列表分为两个子列表进行排序。
快速排序算法 ( QuickSort Algorithm )
The basic concept is to pick one of the elements in the array, called a pivot. Around the pivot, other elements will be rearranged. Everything less than the pivot is moved left of the pivot - into the left partition. Everything greater than the pivot goes into the right partition. At this point, each partition is recursive "quick sorted".
基本概念是选择数组中的元素之一,称为透视 。 围绕枢轴,其他元素将重新排列。 小于枢轴的所有内容都向枢轴的左侧移动-移至左侧分区。 大于枢轴的所有内容都将进入正确的分区。 在这一点上,每个分区都是递归的“快速排序”。
Here's QuickSort algorithm implemented in Delphi:
这是在Delphi中实现的QuickSort算法:
procedure QuickSort(var A: array of Integer; iLo, iHi: Integer) ;var
Lo, Hi, Pivot, T: Integer;
begin
Lo := iLo;
Hi := iHi;
Pivot := A[(Lo + Hi) div 2];repeatwhile A[Lo] < Pivot do Inc(Lo) ;while A[Hi] > Pivot do Dec(Hi) ;if Lo <= Hi thenbegin
T := A[Lo];
A[Lo] := A[Hi];
A[Hi] := T;
Inc(Lo) ;
Dec(Hi) ;end;until Lo > Hi;if Hi > iLo then QuickSort(A, iLo, Hi) ;if Lo < iHi then QuickSort(A, Lo, iHi) ;end;
Usage:
用法:
var
intArray : array of integer;begin
SetLength(intArray,10) ;//Add values to intArray
intArray[0] := 2007;
...
intArray[9] := 1973;//sort
QuickSort(intArray, Low(intArray), High(intArray)) ;
Note: in practice, the QuickSort becomes very slow when the array passed to it is already close to being sorted.
注意:实际上,当传递给它的数组已经接近要排序时,QuickSort会变得非常慢。
There's a demo program that ships with Delphi, called "thrddemo" in the "Threads" folder which shows additional two sorting algorithms: Bubble sort and Selection Sort.
Delphi附带有一个演示程序,在“ Threads”文件夹中称为“ thrddemo”,其中显示了另外两种排序算法:冒泡排序和选择排序。
翻译自: https://www.thoughtco.com/implementing-quicksort-sorting-algorithm-in-delphi-1058220
quicksort算法