Вопрос

I am working on the shell sort, but i could not get the first value in the list sorted. for example. if list{7, 2 ,6, 4, 5), after sorting list{7, 2, 4,5,6}. Could you guys help please! 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;
    }

}
Это было полезно?

Решение

First of all, check the wiki for shellSort.

Since j index never checks 0 index element, first element never compared to following ones. For neater versions refer to here.

Bug is corrected as below.

segmentedInsertionSort(int[] list, int n, int h) {
   .
   .
   while(j >= 0) {
   .
   .
   .
    else
    {
      j = -1;
    }

}

Другие советы

7 is in the position of index 0, your while statement does not execute if j = 0.

To solve this, try a do { } while (j < 0);

do... while... will execute the inner block first, then check if the while statement is true or false.

I tested this in 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;
}

EDIT: Actually this implimentation is buggy, wanted to try a different way than setting j = -1, but alas, that failed.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top