直接插入排序、希尔排序、折半插入排序的c++代码
时间: 2023-07-10 16:41:13 浏览: 151
下面是直接插入排序、希尔排序、折半插入排序的C++代码:
直接插入排序:
```c++
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
```
希尔排序:
```c++
void shellSort(int arr[], int n) {
int gap = 1;
while (gap < n / 3) {
gap = gap * 3 + 1;
}
while (gap > 0) {
for (int i = gap; i < n; i++) {
int key = arr[i];
int j = i - gap;
while (j >= 0 && arr[j] > key) {
arr[j + gap] = arr[j];
j -= gap;
}
arr[j + gap] = key;
}
gap = (gap - 1) / 3;
}
}
```
折半插入排序:
```c++
void binaryInsertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int left = 0, right = i - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] > key) {
right = mid - 1;
} else {
left = mid + 1;
}
}
for (int j = i - 1; j >= left; j--) {
arr[j + 1] = arr[j];
}
arr[left] = key;
}
}
```
以上是三种排序算法的C++代码,可以根据需要进行调用。
阅读全文