#include
#include
#define MAX 20
using namespace std;
void print(int arr[], int max)
{
for (int i = 1; i < MAX + 1; i++) { std::cout << arr[i] << " "; }
std::cout << std::endl;
}
//二分插入排序
void test()
{
srand((unsigned int)time(NULL));
int arr[21] = { 0 };
for (int i = 1; i < MAX + 1; i++)
{
int ret = rand() % 100 + 1;
//二分查找
int head = 1;
int tail = i - 1;
int mid = head + (tail - head) / 2;
while (head <= tail) //循环条件
{
if (ret < arr[mid]) { tail = mid - 1; }
else { head = mid + 1; }
mid = head + (tail - head) / 2;
}
for (int j = i; j >= head; j--) { arr[j] = arr[j - 1]; }
arr[head] = ret;
}
print(arr, MAX);
}
int main()
{
test();
system("pause");
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)