Search code examples
sortingshellsort

I could not be able to get the first value in a list sorted


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;
    }

}

Solution

  • 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;
        }
    
    }