尋找最小的k個數,k個數

來源:互聯網
上載者:User

尋找最小的k個數,k個數
尋找最小的k個數
題目描述:5.尋找最小的k個元素
題目:輸入n個整數,輸出其中最小的k個。

例如輸入1,2,3,4,5,6,7和8這8個數字,則最小的4個數字為1,2,3和4。

演算法1:直接排序,找到最小的k個數

演算法2:將數組a中的前k個數放到數組b中,在將a中後面n-k個數的值與b中最大的數比較,如果a中的數更小,將a中的這個數與b中的最大數交換,當然也可以將b建成一個最大堆

代碼:

/** 尋找最小的k個元素** 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("輸入有誤\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++)//找到b中最大的數{if(j==0){temp=b;}else{if(*temp<*b)temp=b;}b++;}if(*temp>*a) {*temp=*a;}a++;}}int main(void){int a[10]={2,5,99,7,4,1,21,65,96,32};int i;int min_k[5];printf("尋找最小的k個值\n");FindKMin(a,10,min_k,5);printf("尋找到的最小k個值\n");for(i=0;i<5;i++){printf("%d ",min_k[i]);}getchar();    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.