请用C语言写出希尔排序的算法
时间: 2024-04-30 12:17:45 浏览: 12
好的,以下是使用C语言编写的希尔排序算法:
```c
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;
}
}
}
```
其中,`arr`为待排序的数组,`n`为数组的大小。算法首先设定一个增量`gap`,然后对每个`gap`进行插入排序,直到`gap`为1。在每一次排序中,算法将数组按照增量`gap`进行分组,对于每个分组,使用插入排序进行排序,直到所有分组都被排序完成。
希尔排序是一种高效的排序算法,时间复杂度为$O(n \log n)$,但是其实现较为复杂。
相关问题
用C语言写一个希尔排序
希尔排序(Shell Sort)是一种插入排序,它是1959年由Donald Shell发明的。它的基本思想是将数组分割成多个子序列,然后对子序列进行插入排序。
以下是C语言实现的希尔排序算法:
void shellSort(int arr[], int n)
{
// Start with a big gap, then reduce the gap
for (int gap = n/2; gap > 0; gap /= 2)
{
// Do a gapped insertion sort for this gap size.
// The first gap elements a[0..gap-1] are already in gapped order
// keep adding one more element until the entire array is
// gap sorted
for (int i = gap; i < n; i += 1)
{
// add a[i] to the elements that have been gap sorted
// save a[i] in temp and make a hole at position i
int temp = arr[i];
// shift earlier gap-sorted elements up until the correct
// location for a[i] is found
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
arr[j] = arr[j - gap];
// put temp (the original a[i]) in its correct location
arr[j] = temp;
}
}
}
C语言希尔排序并写出排序过程
希尔排序是一种基于插入排序的排序算法,也称为缩小增量排序。它将待排序的数组按照一定的间隔分成若干个子序列,对每个子序列进行插入排序,然后逐渐缩小间隔,直到间隔为1,最后对整个序列进行一次插入排序。
下面是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;
}
// 输出排序过程
printf("gap=%d:\t", gap);
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
}
int main() {
int arr[] = {8, 3, 6, 2, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
shellSort(arr, n);
printf("\n排序结果:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
输出结果如下:
```
gap=3: 2 3 4 5 6 8
gap=1: 2 3 4 5 6 8
排序结果:2 3 4 5 6 8
```
可以看到,排序过程中,数组被分成了三个子序列,分别为{8,2}、{3,4}、{6,5},然后对每个子序列进行插入排序,最后得到了有序数组。