c语言一、编写功能函数(n作为参数) 1、编写函数求出n个数的平均数。 2、编写函数求出n个数的最大数的下标。 3、编写函数求出n个数的最小数的下标。 4、编写函数实现n个数的起泡排序。 5、编写函数实现对n个数的进行顺序查找。(显示依次比较的数据以及比较次数,返回查找结果) 6、编写函数实现对n个数的进行二分查找。(显示依次比较的数据以及比较次数,返回查找结果)
时间: 2023-05-27 12:06:55 浏览: 52
1、求平均数函数:
double average(int n, int arr[]){
int sum = 0;
for(int i = 0; i < n; i++){
sum += arr[i];
}
return (double)sum/n;
}
2、求最大数下标函数:
int maxIndex(int n, int arr[]){
int max = arr[0];
int index = 0;
for(int i = 1; i < n; i++){
if(arr[i] > max){
max = arr[i];
index = i;
}
}
return index;
}
3、求最小数下标函数:
int minIndex(int n, int arr[]){
int min = arr[0];
int index = 0;
for(int i = 1; i < n; i++){
if(arr[i] < min){
min = arr[i];
index = i;
}
}
return index;
}
4、起泡排序函数:
void bubbleSort(int n, int arr[]){
for(int i = 0; i < n-1; i++){
for(int j = 0; j < n-i-1; j++){
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
5、顺序查找函数:
int seqSearch(int n, int arr[], int key){
int count = 0;
for(int i = 0; i < n; i++){
count++;
if(arr[i] == key){
printf("比较次数:%d\n", count);
return i;
}
}
printf("比较次数:%d\n", count);
return -1;
}
6、二分查找函数:
int binarySearch(int n, int arr[], int key){
int count = 0;
int low = 0, high = n-1;
while(low <= high){
count++;
int mid = (low + high)/2;
if(arr[mid] == key){
printf("比较次数:%d\n", count);
return mid;
}
else if(arr[mid] < key){
low = mid + 1;
}
else{
high = mid - 1;
}
}
printf("比较次数:%d\n", count);
return -1;
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)