Algorithm|| Divide and conquer【Find the kth smallest element in a sequence】#02

Find the kth smallest element in a sequence

【Problem Description】

For an unordered sequence containing n elements, please apply the divide and conquer strategy to implement the algorithm for finding the kth (1≤k≤n) small element in the sequence, and the average running time complexity of the algorithm is required to be O(n).

【Algorithm Explanation】

Use the divide and conquer method to solve, similar to quick sort. Store the data in the array a[0...n-1], sort them in ascending order, and the kth smallest element is a[k-1] .

According to the idea of ​​quick sorting , the Partition algorithm is used to divide and decompose, and the two sub-problems a[s...i-1] and a[i+1...t] are recursively solved.

Case 1 : If there is only one element in the array and it is the kth smallest element, then return a[k-1].
Situation 2 : If k-1=i, a[i] is what is required, and a[i] is returned.
Case 3 : If k-1<i, the kth smallest element should be in the a[s...i-1] subsequence, recursively solve in this subsequence and return the result
.
Case 4 : If k-1>i, the kth smallest element should be in the a[i+1...t] subsequence, recursively solve in this subsequence
and return the result.

[Partition Algorithm]

int Partition(int a[], int s, int t)
{
    
    
	int i = s, j = t;
	int temp = a[s];
	while (i != j)
	{
    
    
		while (j > i&&a[j] >= temp)
			j--;
		a[i] = a[j];
		while (i < j&&a[i] <= temp)
			i++;
		a[j] = a[i];
	}
	a[i] = temp;
}

【Complete code】

//寻找一个序列中第k小的元素
#include<iostream>
using namespace std;
#define MAXN 15

int Solve(int a[], int s, int t,int k)
{
    
    
	//划分算法
	int i = s, j = t;
	int temp = a[s];
	if (s < t)
	{
    
    
		while (i != j)
		{
    
    
			while (j > i&&a[j] >= temp)
				j--;
			a[i] = a[j];
			while (i < j&&a[i] <= temp)
				i++;
			a[j] = a[i];
		}
		a[i] = temp;

		//求解
		if (k - 1 == i)
			return a[i];
		else if (k - 1 < i)
		{
    
    
			return Solve(a, s, i - 1, k);
		}
		else return Solve(a, i + 1, t, k);
	}
	else if (s == t && s == k - 1)
		return a[k - 1];
}

int main()
{
    
    
	int n, k;
	int a[MAXN];
	cout << "请输入数组的大小:";
	cin >> n;
	cout << "请依次输入数组数据:";
	for (int i = 0; i <= n; i++)
		cin >> a[i];
	cout << "请输入查找第几小的元素:";
	cin >> k;
	cout << "第" << k << "小的元素为:" << Solve(a, 0, n, k) << endl;
	system("pause");
	return 0;
}

【operation result】

insert image description here

Guess you like

Origin blog.csdn.net/qq_43759081/article/details/121888090