虽然是个老问题,还是基础没有打好,各位高人不要见谅!
接触delphi不久,加上基础比较差。现在终于接触到算法一类的东西了。简单的说就是实现N各自然数的从小到大排序,数据库量在10000以内。求最快的排序方法。
[解决办法]
快速排序吧,参看TStringList.Sort的实现,或者自己看算法书
[解决办法]
10000以内,快速排序还是很快的。
如果数据量大,可以考虑哈希排序。
[解决办法]
一般是快速排序,平均O(nlogn),最坏O(n^2)
更快的是堆排序吧,O(nlogn)的
希尔排序好像平均更快一些
基数排序和桶排序好像最快,但是空间就要求比较大
[解决办法]
能不能贴些代码出来看看啊。。
[解决办法]
找一个《Delphi算法与数据结构》电子版那里面有详细的介绍
[解决办法]
}
}
我们上面提到先定位第一个数,然后整理这个数组,把比这个数小的放到它的左边,大的放右边,然后返回这中间值的位置,下面这函数就是做这个的。
int partition(int n[],int left,int right)
{
int lo,hi,pivot,t;
pivot=n[left];
lo=left-1;
hi=right+1;
while(lo+1!=hi) {
if(n[lo+1]<=pivot)
lo++;
else if(n[hi-1]>pivot)
hi--;
else {
t=n[lo+1];
n[++lo]=n[hi-1];
n[--hi]=t;
}
}
n[left]=n[lo];
n[lo]=pivot;
return lo;
}
这段程序并不难,应该很好看懂,我把过程大致讲一下,首先你的脑子里先浮现一个数组和三个指针,第一个指针称为p指针,在整个过程结束之前它牢牢的指向第一个数,第二个指针和第三个指针分别为lo指针和hi指针,分别指向最左边的值和最右边的值。lo指针和hi指针从两边同时向中间逼近,在逼近的过程中不停的与p指针的值比较,如果lo指针的值比p指针的值小,lo++,还小还++,再小再++,直到碰到一个大于p指针的值,这时视线转移到hi指针,如果hi指针的值比p指针的值大,hi--,还大还--,再大再--,直到碰到一个小于p指针的值。这时就把lo指针的值和hi指针的值做一个调换。持续这过程直到两个指针碰面,这时把p指针的值和碰面的值做一个调换,然后返回p指针新的位置。
我知道我怎么说你们还是不太明白,其实只要看程序就行了,有很多程序的语言是用人类的语言无法表达的。有什么问题,email我:allexit@hotmail.com。
*********************************
数据都保存在Items中
function RSplit(Left, Right: integer): integer;
var
L, H, P, T: integer;
begin
P := Items[Left];
L := Left - 1;
H := Right + 1;
while L + 1 <> H do
begin
if Items[L + 1] <= P then
Inc(L)
else if Items[H - 1] > P then
Dec(H)
else begin
T := Items[L + 1];
Inc(L);
Items[L] := Items[H - 1];
Dec(H);
Items[H] := T;
end;
end;
Items[Left] := Items[L];
Items[L] := P;
Result := L;
end;
procedure QuickSort(iStart, iEnd: integer);
var
Position: integer;
i, j, t: integer;
begin
if iStart < iEnd then
begin
Position := RSplit(iStart, iEnd);
QuickSort(iStart, Position - 1);
QuickSort(Position + 1, iEnd);
end;
end;
Invoke: QuickSort(0,Items.Count -1);
---------------------------------------
{
The following procedure sorts an Array with the
fast Shell-Sort algorithm.
Invented by Donald Shell in 1959,
the shell sort is the most efficient of the O(n2)
class of sorting algorithms
}
{
Die folgende Prozedur Sortiert ein Array mit
dem schnellem Shell-Sort Algorithmus.
}
Procedure Sort_Shell(var a: array of Word);
var
bis, i, j, k: LongInt;
h: Word;
begin
bis := High(a);
k := bis shr 1;// div 2
while k > 0 do
begin
for i := 0 to bis - k do
begin
j := i;
while (j >= 0) and (a[j] > a[j + k]) do
begin
h := a[j];
a[j] := a[j + k];
a[j + k] := h;
if j > k then
Dec(j, k)
else
j := 0;
end; // {end while]
end; // { end for}
k := k shr 1; // div 2
end; // {end while}
end;
[解决办法]
楼主要求最快的排序算法,这个跟具体语言没有关系吧
找个所谓的“最快”排序算法,改写为Delphi的,或者去找个其他人写的算法的函数封装也可以.....
[解决办法]