帮我用C语言编写一个希尔排序的算法
以下是使用C语言编写的希尔排序算法:
#include <stdio.h>
void shellSort(int arr[], int n) {
int gap, i, j, temp;
for (gap = n / 2; gap > 0; gap /= 2) {
for (i = gap; i < n; i++) {
temp = arr[i];
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
arr[j] = arr[j - gap];
}
arr[j] = temp;
}
}
}
int main() {
int arr[] = { 64, 25, 12, 22, 11 };
int n = sizeof(arr) / sizeof(arr[0]);
shellSort(arr, n);
printf("Sorted array: \n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
在这个算法中,我们首先定义了一个shellSort()函数,它包含一个整数数组和数组大小作为参数。在函数中,我们使用希尔排序算法对数组进行排序。然后我们在主函数中定义一个整数数组并初始化它。我们计算数组的大小,然后调用shellSort()函数对数组进行排序。最后,我们使用for循环遍历排序后的数组并将其打印到控制台上。
原文地址: https://www.cveoy.top/t/topic/b2jx 著作权归作者所有。请勿转载和采集!