【发布时间】:2017-12-14 23:12:02
【问题描述】:
打印排序数组中正在搜索的目标元素的索引。如果未找到该元素,则打印应插入的索引,保持数组排序。
我用 C 编写了这个程序,但不明白我哪里出错了,它没有按预期工作。
#include<stdio.h>
int main(){
int n,t,i,k=0,l=0;
int arr[50];
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
scanf("%d",&t);
// Array size should be less than 50
if(n>50){
printf("Array size exceeded");
return 0;
}
//Check array is sorted and has no duplicates
for(i=0;i<n-1;i++){
if(arr[i] == arr[i+1])
k++;
if(arr[i] > arr[i+1])
l++;
}
if(k!=0){
printf("No duplicates allowed");
return 0;
}
if(l!=0){
printf("Array must be sorted");
return 0;
}
//Find element index or print where it should be inserted
for(i=0;i<n;i++){
if(arr[i] == t){
printf("%d",i);
return 0;
}
if(arr[i] > t){
printf("%d",i);
return 0;
}
else{
printf("%d",n+1);
return 0;
}
}
}
【问题讨论】:
-
既然你的数组是排序好的,为什么不用二分查找算法呢?
-
检查
n的值在你开始读入你的数组的值。 -
最后的
for循环没有做你想做的事 -
二分搜索是一个非常好的意见。感谢那。好的,我会尽力让你知道。
标签: c arrays loops sorting search