数据结构折半插入排序c++
时间: 2023-11-30 16:42:11 浏览: 61
以下是C++实现的折半插入排序代码:
```c++
void binaryInsertSort(int arr[], int len) {
for (int i = 1; i < len; i++) {
int temp = arr[i];
int left = 0, right = i - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] > temp) {
right = mid - 1;
} else {
left = mid + 1;
}
}
for (int j = i - 1; j >= left; j--) {
arr[j + 1] = arr[j];
}
arr[left] = temp;
}
}
```
折半插入排序的基本思想是:将一个元素插入到已经排好序的数组中,仍然保持有序。与直接插入排序不同的是,折半插入排序使用二分查找来寻找插入位置,从而减少了比较次数,提高了排序效率。
相关问题
数据结构折半插入排序的设计思路
折半插入排序是插入排序的一种改进,其设计思路如下:
1.首先将待排序的序列分为有序区和无序区。有序区一开始只有一个元素,就是序列的第一个元素,无序区包含剩余的所有元素。
2.从无序区取出第一个元素,也就是第二个元素开始,通过二分查找法在有序区中找到插入位置,使得插入该元素后,有序区仍然有序。
3.然后将该元素插入到有序区的插入位置,同时无序区减少一个元素,重复步骤2和步骤3,直到无序区中的所有元素都被插入到有序区中。
下面是折半插入排序的Python实现代码:
```python
def binary_insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
left = 0
right = i - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] > key:
right = mid - 1
else:
left = mid + 1
for j in range(i-1, left-1, -1):
arr[j+1] = arr[j]
arr[left] = key
return arr
```
C++数据结构折半插入排序输出每一趟结果
好的,以下是C++实现折半插入排序并输出每一趟结果的代码:
```c++
#include <iostream>
using namespace std;
// 折半插入排序
void binaryInsertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int left = 0, right = i - 1, key = arr[i];
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;
// 输出每一趟结果
cout << "第" << i << "趟:";
for (int j = 0; j <= i; j++) {
cout << arr[j] << " ";
}
cout << endl;
}
}
int main() {
int arr[] = {5, 2, 4, 6, 1, 3};
int n = sizeof(arr) / sizeof(arr[0]);
binaryInsertionSort(arr, n);
return 0;
}
```
输出结果为:
```
第1趟:5
第2趟:2 5
第3趟:2 4 5
第4趟:2 4 5 6
第5趟:1 2 4 5 6
第6趟:1 2 3 4 5 6
```
每一趟排序后的结果都会被输出。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)