折半插入排序代码c++
时间: 2023-12-10 14:34:55 浏览: 105
以下是C++实现折半插入排序的代码:
```c++
void binaryInsertSort(int arr[], int len) {
int front, end, temp;
for (int i = 1; i < len; i++) {
temp = arr[i];
front = 0;
end = i - 1;
while (front <= end) {
int mid;
mid = (front + end) / 2;
if (temp < arr[mid]) {
end = mid - 1;
} else {
front = mid + 1;
}
}
for (int z = i; z > front; z--) {
arr[z] = arr[z - 1];
}
arr[front] = temp;
}
}
```
相关问题
直接插入排序、希尔排序、折半插入排序的c++代码
下面是直接插入排序、希尔排序、折半插入排序的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++代码,可以根据需要进行调用。
直接插入排序和折半插入排序。C++完整的代码
下面是直接插入排序和折半插入排序的C++代码示例:
直接插入排序:
```cpp
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;
}
}
```
折半插入排序:
```cpp
int binarySearch(int arr[], int left, int right, int key) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] > key) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
void binaryInsertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
int loc = binarySearch(arr, 0, j, key);
while (j >= loc) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
```
注意,以上代码仅供参考,实际使用时需要根据具体情况进行调整和改进。
阅读全文