我正在进行shell排序,但是我无法将列表中的第一个值排序。例如。如果列出{7,2,6,4,5),则在排序列表{7,2,4,5,6}之后。你能帮忙吗! public static void segmentedInsertionSort(int [] list,int n,int h) { int j;
int temp;
for(int i = h; i < n; i++)
{
j = i - h;
while(j >0)
{
if (list[j] > list[j + h]))
{
temp = list[j];
list[j] = list[j + h];
list[j + h] = temp;
j = j - h;
}
else
{
j = 0;
}
}
}
}
public static void shellSort(int[] list, int n)
{
int h = 1;
while (h < n/3)
{
h = h*3 +1;
}
while(h > 0)
{
segmentedInsertionSort(list, n, h);
h = (h - 1)/3;
}
}
答案 0 :(得分:0)
7位于索引0的位置,如果j = 0,则不执行while语句。
要解决此问题,请尝试do { } while (j < 0);
do ... while ...将首先执行内部块,然后检查while语句是true还是false。
我用perl测试了这个。
#!/usr/bin/perl
use strict;
use warnings;
my @list = (7, 2, 6, 4, 5);
my @newList = shellSort(\@list, $#list);
for (@newList){
print "$_ ";
}
sub shellSort{
my @list = @{ $_[0] };
my $length = $_[1];
my $gap = 1;
while($gap < $length/3){
$gap = ($gap*3) +1;
}
while($gap > 0){
@list = segmentedInsertionSort(\@list, $length, $gap);
$gap = ($gap - 1)/3;
}
return @list;
}
sub segmentedInsertionSort {
my ($li, $length, $gap) = @_;
my @list = @{ $li };
my $j;
my $temp;
for my $i ($gap .. $length){
$j = $i - $gap;
do{
if($list[$j] > $list[$j + $gap]){
$temp = $list[$j];
$list[$j] = $list[$j + $gap];
$list[$j + $gap] = $temp;
$j = $j - $gap;
}
else {
$j = 0;
}
}
while ($j > 0);
}
return @list;
}
编辑: 实际上这个暗示是错误的,想要尝试一种不同于设置j = -1的方式,但唉,失败了。
答案 1 :(得分:0)