1. 程式人生 > >第k小元素問題

第k小元素問題

以下是我能想到的三種方法,若有不足和優化歡迎指出:

#include<iostream>
#define N 10
using namespace std;

//直接排序法:從小到大排序後下標為k的即為第k小元素(下標從1算起)
int fun1(int a[], int n,int k)
{
	for (int i = 1; i < n; i++)
	{
		for (int j = i + 1; j < n; j++)
		{
			if (a[i]>a[j])
			{
				int temp = a[i];
				a[i] = a[j];
				a[j] = temp;
			}
		}
	}
	return a[k];
}
//直接尋找法:第k小元素一定存在k-1個比它小的
int fun2(int a[], int n, int k)
{
	for (int i = 1; i < n; i++)
	{
		int count = 0;
		for (int j = 1; j < n; j++)
		{
			if (a[j]<a[i])
			{
				count++;
			}
        }
		if (count == k - 1)
		{
			return a[i];
		}
	}
}

//快速排序法:即先選定一個軸線位置s,將所有元素分為兩部分,比它小的放左邊,比它大的放右邊。如果s==k,返回;s>k去左邊找;s<k去右邊找。
int quick_sort(int a[], int l,int h)    //快速排序的實現
{
		int low = l, high = h;
		while (low < high)
		{
			while (low < high&&a[low] < a[high])
			{
				high--;
			}
			if (low < high)
			{
				int temp = a[low];
				a[low] = a[high];
				a[high] = temp;
				low++;
			}
			while (low < high&&a[low] < a[high])
			{ 
				low++;
			}
			if (low < high)
			{
				int temp = a[low];
				a[low] = a[high];
				a[high] = temp;
				high--;
			}
		}
		return low;
}
int fun3(int a[], int low,int high, int k)  //尋找第k小
{
	int s = quick_sort(a, low,high);   
	if (s == k)
	{
		return a[k];
	}
	else if (s > k)
	{
		return fun3(a, low,s - 1, k);
	}
	else
	{
		return fun3(a, s + 1, high,k);
	}
}

int main()
{
	int a[N] = { 0,12,23,1,234,56,2,13,87,99 };
	int k;
	cin >> k;
	cout << fun1(a, N, k) << endl;
	cout << fun2(a, N, k) << endl;
	cout << fun3(a, 1, N - 1, k) << endl;
	return 0;

}