Find the minimum k count and k count

Source: Internet
Author: User

Find the minimum k count and k count
Find the minimum k count
Description: 5. Find the minimum k elements.
Question: Enter n integers and output the smallest k integers.

For example, if you enter the 8 numbers 1, 2, 3, 5, 6, 7, and 8, the minimum four digits are 1, 2, 3, and 4.

Algorithm 1: Sort directly and find the minimum k Number

Algorithm 2: place the number of the first k in array a into array B. Compare the value of the number of n-k in array a with the maximum number in array B. If the number in array a is smaller, exchange the number in a with the maximum number in B. Of course, B can also be built into a maximum heap.

Code:

/** Find the smallest k elements ** author: xiaozhi xiong ** date: 2014-02-11 **/# include "stdio. h "# include" string. h "# include" stdlib. h "# include" stdio. h "# include" string. h "# include" stdlib. h "void FindKMin (int * a1, int len_a, int * b1, int len_ B) {int I; int j; int * temp; int * a; int * B; a = a1; B = b1; if (len_a <len_ B | len_a <0) {printf ("incorrect input \ n"); return;} for (I = 0; I <len_ B; I ++) {* B = * a; B ++; a ++;} for (I = len_ B; I <len_a; I ++) {B = b1; for (j = 0; j <len_ B; j ++) // find the maximum number in B {if (j = 0) {temp = B;} else {if (* temp <* B) temp = B;} B ++;} if (* temp> *) {* temp = * a;} a ++ ;}} int main (void) {int a [10] = }; int I; int min_k [5]; printf ("find the smallest k values \ n"); FindKMin (a, 10, min_k, 5 ); printf ("minimum k found value \ n"); for (I = 0; I <5; I ++) {printf ("% d ", min_k [I]);} getchar (); return 0 ;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.