题目:输入n个整数,输出其中最小的k个。
例如输入1,2,3,4,5,6,7和8这8个数字,则最小的4个数字为1,2,3和4。
// 查找最小的k个元素.cpp : Defines the entry point for the console application. // /* 题目:输入n个整数,输出其中最小的k个。 例如输入1,2,3,4,5,6,7和8这8个数字,则最小的4个数字为1,2,3和4。 */ #include "stdafx.h" #include <iostream> #include <string> #define MAX_SIZE 256 using namespace std; void selectMinCountElement(int a[],int count,int minCount) { if(minCount > count)
{
return;
}
//冒泡排序 for (int i=0;i<count;i++) { for (int j=i+1;j<count;j++) { if (a[i] > a[j]) { int temp = a[j]; a[j] = a[i]; a[i] = temp; } } } cout << "排序后的整数为:" << endl; for (int i=0; i<count;i++) { cout << a[i] << " "; } cout << endl; cout << "最小的" << minCount << "数字为:" << endl; for (int i=0; i<minCount; i++) { cout << a[i] << " "; } cout << endl; } int _tmain(int argc, _TCHAR* argv[]) { int count = 0;//用来记录输入多少个整数 cout << "需要多少个整数:" << endl; cin >> count; int a[MAX_SIZE]; cout << "请输入" << count << "个整数:" << endl; for (int i=0; i<count; i++) { cin >> a[i]; } cout << "您输入的整数为:" << endl; for (int i=0; i<count; i++) { cout << a[i] << " "; } cout << endl; cout << "请输入需要输出最小的几个数字:" << endl; int minCount = 0; cin >> minCount; selectMinCountElement(a,count,minCount); system("pause"); }