希尔排序代码实现

// 希尔排序1
void ShellSort1(int data[], int count)
{
    int step = 0;
    int auxiliary = 0;

    for (step = count / 2; step > 0; step /= 2)
    {
        for (int i = 0; i < step; ++i)
        {
            for (int j = i + step; j < count; j += step) 
            {
                 // 直接插入排序
                if (data[j] < data[j - step])
                {
                    auxiliary = data[j];
                    int k = j - step;

                    while (k >= 0 && data[k] > auxiliary)
                    {
                        data[k + step] = data[k];
                        k -= step;
                    }

                    data[k + step] = auxiliary;
                }
            }
        }
    }
}

// 希尔排序2
void ShellSort2(int data[], int count)
{
    int step = 0;
    int auxiliary = 0;

    for (step = count / 2; step > 0; step /= 2)
    {
        // 从数组第step个元素开始
        for (int i = step; i < count; i++) 
        {
            // 每个元素与自己组内的数据进行直接插入排序
            if (data[i] < data[i - step]) 
            {
                auxiliary = data[i];
                int j = i - step;

                while (j >= 0 && data[j] > auxiliary)
                {
                    data[j + step] = data[j];
                    j -= step;
                }

                data[j + step] = auxiliary;
            }
        }
    }
}

 

posted on 2012-12-31 10:01  zhuyf87  阅读(2112)  评论(0编辑  收藏  举报

导航