zoukankan      html  css  js  c++  java
  • 查找最小的k个元素

    题目:输入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"); }
  • 相关阅读:
    PIL PNG格式通道问题的解决方法
    opencv-python 学习初探2 去图片水印
    Appium、selenium与Robot Framework
    性能监控0
    XML
    Python3 读取和写入excel
    Python识别字符型图片验证码
    python进程、线程、协程
    算法和程序
    Zigbee
  • 原文地址:https://www.cnblogs.com/study-programmer/p/3409037.html
Copyright © 2011-2022 走看看