用函数编程实现在一个按升序排序的数组中查找x应插入的位置,将x插入数组中,使数组元素仍按升序排序
此代码采用选择法排序和折半法查找x的位置
#include<stdio.h>
#define N 40//可随意更改N的值,但不能超过n+1的值
int ReadScore(int score[]);
void DataSort(int score[],int n);
void PrintScore(int score[],int n);
void search(int score[],int x,int n);
int main(void)
{
int score[N],n,x;
n = ReadScore(score);
printf("Total number are %d\n",n);
DataSort(score,n);
printf("Sorted scores:");
PrintScore(score,n);//打印输入后的数组的排序
printf("\nInput x:");
scanf("%d",&x);
search(score,x,n);
PrintScore(score,n+1);//打印把x插入数组某个位置后,数组的排序,此时n+1
return 0;
}
//函数功能:输入某数,当输入负值时,结束输入,返回个数
int ReadScore(int score[])
{
int i = -1;
do{
i++;
printf("Input score:");
scanf("%d",&score[i]);
}while(score[i]>=0);
return i;
}
//函数功能:按交换法将数组score的元素值按从低到高排序
void DataSort(int score[],int n)
{
int i,j,k,temp;
for(i=0;i<n-1;i++)
{
k = i;
for(j=i+1;j<n;j++)
{
if(score[j]<score[k])
{
k = j;
}
}
if(k!=i)
{
temp = score[k];
score[k] = score[i];
score[i] = temp;
}
}
}
//函数功能:打印数字
void PrintScore(int score[],int n)
{
int i;
for(i=0;i<n;i++)
printf("%d ",score[i]);
}
//函数功能:找到x应该放的位置
void search(int score[],int x,int n)
{
int low = 0,high = n-1,mid;
int pos;
if(x<=score[low])//若x比数组的第一个数还小,就把x的下标变成0
{
for(int i=n+1;i>0;i--)//先将0之后的下标变换位置
{
pos = score[i];
score[i] = score[i-1];
score[i-1] = pos;//下一个等于上一个的值
}
score[low] = x;
}
else if(x>=score[high])//若x比数组的最后一个数还大,就把x的下标变成n
{
score[n] = x;
}
else//若x是在数组中间的某一位置,就做以下循环
{
do{
mid = low + (high - low) / 2;
if(x>score[mid])
low = mid + 1;
else if(x<score[mid])
high = mid - 1;
else if(x==score[mid])
break;
}while(low<high && high-low!=1);
for(int i=n+1;i>mid+1;i--)
{
pos = score[i];
score[i] = score[i-1];
score[i-1] = pos;//下一个等于上一个的值
}
score[mid+1] = x;
}
}
参考输入和输出
1、第一种情况:当x的值小于score[0]的值时
2、第二种情况:当x的值大于数组的最大值时
3、第三种情况:当x的值处于数组中间时
总结:测试时应考虑齐所有的情况,增强代码的完整性,找到每种情况的排序方法。