Shell Sort Algorithm Implementation in C

mail@pastecode.io avatar
unknown
c_cpp
10 days ago
930 B
1
Indexable
Never
// 使用希尔排序算法对数组进行排序
void shell_sort(int arr[], int length)
{
    int gap, currentIndex, comparisonIndex, tempValue;

    // 从初始步长开始,逐步缩小步长
    for (gap = length / 2; gap > 0; gap /= 2)
    {
        // 对间隔为 gap 的元素进行插入排序
        for (currentIndex = gap; currentIndex < length; currentIndex++)
        {
            // 存储当前元素的值
            tempValue = arr[currentIndex];

            // 对比并移动与当前元素相隔 gap 的元素
            for (comparisonIndex = currentIndex - gap; 
                 comparisonIndex >= 0 && arr[comparisonIndex] > tempValue; 
                 comparisonIndex -= gap)
            {
                arr[comparisonIndex + gap] = arr[comparisonIndex];
            }

            // 将存储的值插入到正确的位置
            arr[comparisonIndex + gap] = tempValue;
        }
    }
}
Leave a Comment