【发布时间】:2021-03-24 10:30:41
【问题描述】:
编写一个程序,对一维数组的元素进行降序排序,并实现线性搜索 同一个数组。排序和搜索操作都应该在一个用户定义的函数中完成:“任务”。 因此,为了实现所需的功能,将数组传递给函数:Task() from main() using Pass by 参考/或地址方法。
【问题讨论】:
标签: arrays c function sorting search
编写一个程序,对一维数组的元素进行降序排序,并实现线性搜索 同一个数组。排序和搜索操作都应该在一个用户定义的函数中完成:“任务”。 因此,为了实现所需的功能,将数组传递给函数:Task() from main() using Pass by 参考/或地址方法。
【问题讨论】:
标签: arrays c function sorting search
在这段代码中,我使用了一个布尔函数,这个函数按降序排列数组的元素,然后他检查值是否存在于值中(如果值存在则返回true,如果值不存在则返回false'不存在)
#include <stdio.h>
#include <stdbool.h>
bool linear_search(int N,int A[N],int VAL);
int main()
{
int VAL,POS,N;
do
{
printf("Give me the length of array : ");
scanf("%d", &N );
}while(N<1);
int A[N];
for(int i=0;i<N;i++)
{
printf("Element number %d : ", i);
scanf("%d", &A[i]);
}
printf("Element of find : ");
scanf("%d", &VAL );
printf("\nDisplay the array \n");
for (int i=0; i<N; i++)
{
printf("%d ", A[i]);
}
if(linear_search(N,A,VAL)==true)
{
printf("\n\nThe value %d exist in this array \n",VAL);
}
else
{
printf("\n\nThe value does not exist in this array \n");
}
printf("\n");
return 0;
}
bool linear_search(int N,int A[N],int VAL)
{
for(int i=0;i<N;i++)
{int temp=0;
for(int j=0;j<N;j++)
{
if(A[j]>A[i])
{
temp=A[i];
A[i]=A[j];
A[j]=temp;
}
}
}
int POS = -1;
for(int i=0 ; (i<N)&&(POS==-1) ; i++)
{
if (A[i]==VAL)
{
POS=i;
}
}
if (POS==-1)
{
return false;
}
return true;
}
【讨论】: