写一个用二分按照学生成绩排名的程序c++
时间: 2023-05-23 12:00:57 浏览: 53
Sure, here is an example implementation of a C program that sorts students' scores using binary search:
```c
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
return *(int*)a - *(int*)b;
}
int binary_search(int *arr, int n, int x) {
int l = 0, r = n - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] == x) return mid;
if (arr[mid] < x) l = mid + 1;
else r = mid - 1;
}
return -1;
}
int main() {
int n;
scanf("%d", &n);
int scores[n];
for (int i = 0; i < n; i++) {
scanf("%d", &scores[i]);
}
qsort(scores, n, sizeof(int), cmp);
printf("Sorted scores:\n");
for (int i = n - 1; i >= 0; i--) {
printf("%d\n", scores[i]);
}
int x;
printf("Enter a score to search for:\n");
scanf("%d", &x);
int idx = binary_search(scores, n, x);
if (idx == -1) {
printf("Score not found!\n");
} else {
printf("Score found at index %d.\n", idx);
}
return 0;
}
```
This program takes in N scores as input, sorts them using quicksort, and then prints them out in descending order. It also prompts the user to search for a specific score using binary search and returns the index at which it was found.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)