用C++写一个希尔排序
时间: 2023-12-29 07:49:03 浏览: 114
c++希尔排序
下面是用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[] = { 12, 34, 54, 2, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original Array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
shellSort(arr, n);
printf("\nSorted Array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
运行结果:
```
Original Array:
12 34 54 2 3
Sorted Array:
2 3 12 34 54
```
阅读全文