简体   繁体   English

Shell排序未对数组的第一个元素进行排序

[英]Shell sort is not sorting the first element of an array

When my sort is run on this data {7,8,4,2,3,9,5,8,4,1} only the first element is not put in its correct place. 在此数据{7,8,4,2,3,9,5,8,4,1}上运行我的排序时,只有第一个元素没有放在正确的位置。 How can I fix this? 我怎样才能解决这个问题? Thanks for the help. 谢谢您的帮助。

public void segmentedInsertionSort(int[] array, int size, int h)
    {
        int temp;

        for(int i = h + 1 ;i < size;i++)
        {
            int j = i - h;


            while(j > 0)
            {
                if(array[j+h] < array[j])
                {
                    temp = array[j];
                    array[j] = array[j+h];
                    array[j+h] = temp;
                    j = j - h;
                }
                else
                {
                    j = 0;
                }
            }
        }
    }

    public void shellSort(int[] array, int size)
    {
        int h = size/2;

        while(h > 0)
        {
            segmentedInsertionSort(array,size,h);
            h = h/2;
        }            
    }
for(int i = h + 1 ;i < size;i++)
        {
            int j = i - h;


            while(j > 0)
            {
                if(array[j+h] < array[j])
                {
                    temp = array[j];
                    array[j] = array[j+h];
                    array[j+h] = temp;
                    j = j - h;
                }

In this part, you define i = h + 1 and then increase i value. 在这一部分中,定义i = h + 1,然后增加i值。 So, so the j value is never less than 1 when the sort runs. 因此,排序运行时j的值永远不会小于1。 Therefore, it never processes the first element of array. 因此,它永远不会处理数组的第一个元素。 You need to fix this part. 您需要修复此部分。

I think you have misvalued some variables.Your variable j never reaches index 0 so as to compare 7 with any other value in this Comparison Sort. 我认为您已对某些变量进行了错误估价。您的变量j从未达到索引0,因此无法将7与该比较排序中的任何其他值进行比较。

Change: 更改:

for(int i = h +1 ;i < size;i++) to for(int i = h ;i < size;i++) for(int i = h +1 ;i < size;i++)for(int i = h ;i < size;i++)

And

while(j > 0) to while(j >= 0) while(j > 0)while(j >= 0)

else { j = 0; }

to else{ j = -1; } else{ j = -1; } else{ j = -1; }

Final Code looks like: 最终代码如下:

` void segmentedInsertionSort(int arr[], int size, int h)
{
    int temp;

    for(int i = h  ;i < size;i++)
    {
        int j = i-h ;


        while(j >= 0)
        {
            if(arr[j+h] < arr[j])
            {
                temp = arr[j];
                arr[j] = arr[j+h];
                arr[j+h] = temp;
                j = j - h;
            }
            else
            {
                j = -1;
            }
        }
    }
}
void shellSort(int arr[], int size)
{
    int h = size/2;

    while(h > 0)
    {
        print(arr);
        segmentedInsertionSort(arr,size,h);
        h = h/2;
    }            
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM