视频讲解在这里:
p18 第9题 c语言实现王道数据结构课后代码题_哔哩哔哩_bilibili
要求算法完成用最少时间,我们可以使用折半查找
本题代码如下
void search(int a[],int x)
{
int low = 0;
int high = n - 1;
int mid=0;
while (low <= high)
{
mid = (high + low) / 2;
if (a[mid] == x)
break;
else if (a[mid] > x)
high = mid - 1;
else
low = mid + 1;
}
if (a[mid]==x&& mid != n - 1)
{
int temp = a[mid];
a[mid] = a[mid + 1];
a[mid + 1] = temp;
}
if (low > high)
{
int i = 0;
for (i = n - 1; i > high; i--)
a[i + 1] = a[i];
a[i + 1] = x;
}
}
完整测试代码
#include
int n = 10;
int a[10] = { 1,2,3,4,5,6,8,9,10};
void search(int a[],int x)
{
int low = 0;
int high = n - 1;
int mid=0;
while (low <= high)
{
mid = (high + low) / 2;
if (a[mid] == x)
break;
else if (a[mid] > x)
high = mid - 1;
else
low = mid + 1;
}
if (a[mid]==x&& mid != n - 1)
{
int temp = a[mid];
a[mid] = a[mid + 1];
a[mid + 1] = temp;
}
if (low > high)
{
int i = 0;
for (i = n - 1; i > high; i--)
a[i + 1] = a[i];
a[i + 1] = x;
}
}
int main()
{
int i = 0;
for (i = 0; i < 9; i++)
printf("%d ", a[i]);
search(a,6);
printf("\n");
for (i = 0; i < 9; i++)
printf("%d ", a[i]);
return 0;
}