将HeapSort和ShellSort从C转换为Pascal



我对两种排序有问题——Heap和Shell。我在C中有一些代码,我需要尝试在过程主体中使用相同的命令(比如当我在C使用"for loop"时,我也想对Pascal使用"for loop"(。我试过了,但排序并不像在C中那样工作。在C中,对于大小为40000的数组,一切都很好。

C中ShellSort的代码,其中参数"n"是数组的大小:

shellSort(int n){
int shift,pom,j,i;
shift = n/2;
while(shifta>0){
for (i = shift; i < n; i += 1){
pom=arr[i];
j=i;
while((j>=shift) && (arr[j-shift]>pom)){
arr[j] = arr[j - shift]; 
j=j-shift;
}
arr[j]=pom;
}
shift= shift / 2;
}
}

Pascal 中的声明

arr :array[0..22] of integer;       
size:integer =23; 

Pascal中具有相同参数的代码:

procedure ShellSort(n:integer); 
Var
shift , pom : Integer;
Begin
shift:=n div 2 ; 
While shift>0 Do
Begin
For i:=shift to n Do
Begin
pom:=arr[i];
j:=i;
While (j>=shift) and (arr[j-shift]>pom) Do
Begin
arr[j]:=arr[j-shift];
j:= j-shift
End;
arr[j]:=pom;
End;
shift:=shift div 2;
End;
End;  

C:中堆排序的代码

heapSort() {
int N = size;
int k;
int pom;
for (k = N / 2; k > 0; k--) {
downHeap(k, N);
}
do {
pom = arr[0];
arr[0] = arr[N - 1];
arr[N - 1] =  pom;
N = N - 1;
downHeap(1, N);
} while (N > 1);
}
downHeap(int k, int N) {
int T = arr[k - 1];
while (k <= N / 2) {
int j = k + k;
if ((j < N) && (arr[j - 1] < arr[j])) {
j++;
}
if (T >= arr[j - 1]) {
break;
} else {
arr[k - 1] = arr[j - 1];
k = j;
}
}
arr[k - 1] = T;
}

Pascal中堆排序的代码:

procedure downHeap(k:integer;N:integer);
var
T:integer;
begin
T:=arr[k-1];
while(k<= (N div 2)) do
begin
j:=k+k;
if ((j<N) and (arr[j-1]<arr[j])) then
begin
j:=j+1;
end;
if (T>=arr[j-1]) then
begin
exit;
end
else
begin
arr[k-1]:=arr[j-1];
k:=j;
end;
end;
arr[k-1]:=T;
end;
procedure heapSort;
var
n, pom:integer;
begin
n:=size;
for i:=n div 2 downto 1 do
begin
downHeap(i,n);
end;
repeat
begin
pom:=arr[0];
arr[0]:=arr[n-1];
arr[n-1]:=pom;
n:=n-1;
downHeap(1,n);
end;
until n>1;
end;   

Pascal输出:

Unsorted array
10 9 8 7 6 5 4 3 3 2 1 0 15 15 15 15 14 18 99 1 19 95 95
BubbleSort
0 1 1 2 3 3 4 5 6 7 8 9 10 14 15 15 15 15 18 19 95 95 99
HeapSort
95 95 15 18 95 15 15 15 18 19 95 0 5 4 15 3 14 7 3 1 2 1 99
ShellSort
0 0 1 1 2 3 3 4 5 7 14 15 15 15 15 15 18 18 19 95 95 95 95
Expected
0 1 1 2 3 3 4 5 6 7 8 9 10 14 15 15 15 15 18 19 95 95 99 

我真的很沮丧。

将注释转换为答案

在Shell排序中,C循环是:

for (i = shift; i < n; i += 1){

Pascal循环是

For i:=shift to n Do

Pascal循环循环的频率太高;它需要:

For i := shift to n-1 Do

假设表达式在循环限制中是允许的——如果不允许,您需要一个额外的变量,大致如下:

var ub: integer;
ub := n - 1;
For i := shift to ub Do

C for循环比Pascal for循环更通用、更灵活。

在堆排序中,C循环是:

do { … } while (N > 1);

你已经把它翻译成

repeat … until n > 1;

终止条件错误;until相当于while not,因此您需要:

repeat … until n <= 1;

我从来没有仔细检查过整个Pascal代码——我也没有Pascal编译器可以测试——所以可能还有其他问题需要解决,但这两个问题应该会让你继续前进。(请确保您已经检查了forrepeat … until的所有出现情况,以查找此处列出的问题。(

最新更新