#include <iostream>
using namespace std;
int main()
{
const int MAXN = 100;
int a[MAXN];
int n;
cin >> n;
int i, j;
int low, high, mid;
for(i = 1; i <= n; i++)
{
cin >> a[i];
}
int tmp;
for(i = 2; i <= n; i++)
{
tmp = a[i];
low = 1;
high = i-1;
while(low <= high)
{
mid = (low + high) / 2;
if(a[mid] < a[i])
low = mid + 1;
else
high = mid - 1;
}
for(j = i-1; j >= low; j--)
a[j+1] = a[j];
a[low] = tmp;
}
for(i = 1; i <= n; i++)
cout << a[i] << " ";
return 0;
}
虽然时间上仍为O(n^2),但是提高了查找插入位置的效率。
时间: 2024-10-14 04:35:57