寻找第k大数

/*************************************************************************
    > File Name: k_fenshu.cpp
    > Author: wangzhicheng
    > Mail: 2363702560@qq.com
    > Created Time: Sun 18 Jan 2015 10:47:12 PM WST
	This is a free program, you can modify or redistribute it under the term of GNU
 ************************************************************************/
// search the k_th max number
// for example, 3, 0, 1, 2, the 1 max number is 3, the 2 max number is 2
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
/*
 * @purpose:partition a array, this is generally included in quick sort
 * */
int partition(vector<int>&v, int start, int end) {
	int i, j;
	int k;
	int tmp;
	i = start;
	j = end;
	tmp = v[i];

	while(i < j) {
		while(i < j && v[j] > tmp) j--;
		if(i < j) v[i++] = v[j];
		while(i < j && v[i] < tmp) i++;
		if(i < j) v[j--] = v[i];
	}
	v[i] = tmp;

	return i;
}
void find_k_max(vector<int>&v, int start, int end, int k_th, int &k_max) {
	int pivot;
	int k;
	if(start <= end) {
		pivot = partition(v, start, end);
		k = end - pivot + 1;
		if(k == k_th) k_max = v[k];
		else if(k > k_th) find_k_max(v, pivot + 1, end, k_th, k_max);
		else find_k_max(v, start, pivot - 1, k_th - k, k_max);

	}
}
int main() { 
	int n;
	int k_th, k_max;
	int i;
	cout << "number = ";
	cin >> n;
	cout << "k_th = ";
	cin >> k_th;
	if(k_th < 1 || k_th > n) {
		cerr << "imput error...!" << endl;
		exit(1);
	}
	vector<int>v(n);
	for(i = 0;i < n;i++) {
		cout << i << " = ";
		cin >> v[i];
	}
	find_k_max(v, 0, n - 1, k_th, k_max);
	cout << "k_max = " << k_max << endl;

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值