遞推--找數字

萌新待開發發表於2020-11-02

輸入一行數字和一個k值,輸出前k個小的數字

 

#include<iostream> 
#include<cstring> 
using namespace std;  
int a[1000];
int n = 0, k;

void swap(int &a, int &b)
{
	int temp = a;
	a = b;
	b = temp;
}

int partition(int l, int r)
{
	int i = l, j = r + 1;
	while (true){
		while (a[++i]<a[l] && i<r);
		while (a[--j]>a[l]);
		if (i >= j)
			break;
		swap(a[i], a[j]);

	}
	swap(a[l], a[j]);

	return j;
}

void quick_sort(int l, int r)
{
	if (l<r){
		int p = partition(l, r);
		if (p >= 9)
			quick_sort(l, p - 1);
		else if (p <= 4)
			quick_sort(p + 1, r);
		else{
			quick_sort(l, p - 1);
			quick_sort(p + 1, r);
		}
	}
}

int main()
{

	while (cin >> k){
		if (k == 0)
			break;
		a[n++] = k;
	}
	quick_sort(0, n - 1);
	for (int i = 4; i <= 9; i++)
		cout << a[i] << endl;
	return 0;
}

 

相關文章