希尔排序算法c++简易
时间: 2023-12-18 15:29:56 浏览: 96
```c++
#include <iostream>
using namespace std;
// 希尔排序函数
void shellSort(int arr[], int n) {
// 初始步长为数组长度的一半
for (int gap = n / 2; gap > 0; gap /= 2) {
// 对每个步长进行插入排序
for (int i = gap; i < n; i++) {
int temp = arr[i];
int j;
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]);
cout << "Array before sorting: \n";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
shellSort(arr, n);
cout << "\nArray after sorting: \n";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
```
阅读全文