SWUSTOJ #616 排序查找

題目

用選擇法對N個學生的成績按從大到小的順序排序,N個學生的成績整數用scanf 輸入,輸入的成績在[0,100]之間。排序完成後,輸入一個成績,要求用逐個比較查找的方式找出該成績是該組中第幾個元素的值(即第幾名)。如果該成績不在數組中,則輸出“no this score!”。 要求: 1、把排序算法寫成函數形式,在主函數中輸入N個數據,然後調用排序函數排序。 2、在排序過程中儘量減少數據的交換和移動。 3、把查找算法寫成函數形式,在主函數中輸入1個數據,然後調用查找函數查找。

輸入

輸入共有三行:第一行是一個數N(N < 50),表示學生的人數; 第二行輸入N個學生的成績; 第三行輸入一個數m(你要查找的成績)

輸出

第一行輸出N個已經排好序的成績,每兩個成績之間有一個空格隔開,每10個數據換一行(由大到小排列)。 第二行輸出你要查找的成績的名次(如果成績相同,則並列)。具體的見Sample Output。

樣例輸入

15
23 32 43 54 65 65 78 87 98 87 76 76 76 55 65
87
23
32 43 54 89 89 78 89 78 55 65 76 87 87 87 65 65 89 86 65 78 54 57 54
86

樣例輸出

98 87 87 78 76 76 76 65 65 65
55 54 43 32 23
2
89 89 89 89 87 87 87 86 78 78
78 76 65 65 65 65 57 55 54 54
54 43 32
8

源代碼

#include <stdio.h>
#include <algorithm>

using namespace std;

const int N = 10005;
int a[N], m;
int cmp(int a, int b)
{
	return a >= b;
}
int f(int i)
{
	return a[i] <= m;
}
int find(int l, int r)
{
	int i = l;
	int j = r;
	while(i < j)
	{
		int mind = i+j >> 1;
		if(f(mind))
			j = mind;
		else
			i = mind+1;
	}
	return i;
}

int main()
{
	int n;
	scanf("%d", &n);
	for(int i=0; i<n; i++)
	{
		scanf("%d", &a[i]);
	}
	scanf("%d", &m);
	sort(a, a+n, cmp);
	for(int i=0; i<n; i++)
	{
		if((i+1)%10 == 0)
			printf("%d\n", a[i]);
		else if(i == n-1)
		{
			printf("%d\n", a[i]);
		}
		else
			printf("%d ", a[i]);
	}
	int ans = find(0, n-1);
	if(a[ans] == m)
		printf("%d\n", ans+1);
	else
		printf("no this score!\n");
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章