c 取N中最大的K个数

// max_k_number.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <stdlib.h>

using namespace std;

void partition(int a[], int s,int t,int &k)  
{//devide the array into three parts  
	int i,j,x;  
	x=a[s];    //get the element
	i=s;        //get the initial value 
	j=t;  
	do  
	{  
		while((a[j]<x)&&i<j) j--;   //check from right to left ,if it is smaller ,do thing.
		if(i<j) a[i++]=a[j];           //if it is bigger move right
		while((a[i]>=x)&&i<j) i++;     //check from left to right ,if it is bigger , do thing
		if(i<j) a[j--]=a[i];           //if it is smaller move left

	}while(i<j); //untill i equals j
	a[i]=x;      // get the point value
	k=i;  
}  

int FindKMax(int a[],int low,int high,int k)
{ // k is the value number of the max
	//high is the position of the max number
	//low is the position of the small number
	int q;
	int index=-1;
	if(low < high)  
	{  
		partition(a , low , high,q);  
		int len = q - low + 1;  
		if(len == k)  
			index=q;   
		else if(len < k)   
			index= FindKMax(a , q + 1 , high , k-len);     
		else 
			index=FindKMax(a , low , q - 1, k);  
	}  
	return index;

}


int _tmain(int argc, _TCHAR* argv[])
{

	int a[]={20,100,4,2,87,9,8,5,46,26};  
	int Len=sizeof(a)/sizeof(int); 
	int K=3;
	FindKMax(a , 0 , Len- 1 , K) ;    
	for(int i = 0 ; i < K ; i++)  
		cout<<a[i]<<" ";  

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值