Skip to content

Latest commit

 

History

History
45 lines (42 loc) · 1.11 KB

C++归并排序并输出第k小的元素.md

File metadata and controls

45 lines (42 loc) · 1.11 KB

在这里插入图片描述

//Author:PanDaoxi
#include <iostream>
using namespace std;
const int maxn=101;
int a[maxn],r[maxn];
void merge(int left,int right){
	{
		if(left==right) return;
		int mid=(left+right)/2;
		merge(left,mid);
		merge(mid+1,right);
		int i=left,j=mid+1,k=left;
		while(i<=mid&&j<=right){ 
			if(a[i]<a[j]) r[k++]=a[i++];
			else r[k++]=a[j++];
		}
		while(i<=mid){
			r[k++]=a[i++]; 
		}
		while(j<=right){ 
			r[k++]=a[j++];
		}
	}
	for(int i=left;i<=right;i++){
		a[i]=r[i];
	}
	return;
} 
int main(){
	int n,k;
	cin>>n>>k;
	for(int i=1;i<=n;i++){
		cin>>a[i];
	}
	merge(1,n);
	cout<<a[k]<<" ";
	return 0;
} 

在这里插入图片描述