折半插入排序
1.概念和图解
1.1 概念简介
折半插入排序是对直接插入排序的升级,直接插入排序的时间复杂度主要在比较和移动上,折半插入排序根据这两个方面进行改进。
1.2 算法思路
在将一个新元素插入已排好序的数组的过程中,寻找插入点时,将待插入区域的首元素设置为arr[low],末元素设置为arr[high],则每轮比较时将待插入元素与arr[mid],其中mid=(low+high)/2相比较,如果比参考元素小,则选择arr[low]到arr[m-1]为新的插入区域(即high=mid-1),否则选择arr[mid+1]到arr[high]为新的插入区域(即low=m+1),如此直至low<=high不成立,即将此位置之后所有元素后移一位,并将新元素插入arr[high+1]。
1.3 例子图解
例子:用折半插入排序算法排序 36,80,45,66,22,9,16,36
2.代码实现
/**
* @Author: lwj
* @Date: 2022-08-31 15:45:22
* @FilePath: /Linux_C_C-plus-plus/数据结构与算法(C++)/算法/排序算法/binaryInsertSort.cpp
* @Description:折半插入排序
**/
#include <iostream>
template <typename Type>
void print(const Type &arr, int size) //打印数组
{
for (int i = 0; i < size; i++)
{
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
template <typename Type>
void binaryInsertSort(Type arr[], int size)
{
int pos, j, low, high, mid;
Type tmp;
for (pos = 1; pos < size; pos++)
{
tmp = arr[pos], low = 0, high = pos - 1;
while (low <= high)
{
mid = (low + high) / 2; //求有序序列的中间值,
if (tmp < arr[mid])
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
for (j = pos - 1; j >= low; j--)
{
arr[j + 1] = arr[j];
}
arr[low] = tmp;
}
}
int main()
{
int arr[] = {36, 80, 45, 66, 22, 9, 16, 36};
int count = sizeof(arr) / sizeof(arr[0]);
binaryInsertSort(arr, count);
print(arr, count);
return 0;
}