POJ2388-排序水题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ltyqljhwcm/article/details/52469329

1.题目:

奇数个数排序求中位数

2.三种排序方法:


1.快排 700k 16Ms

#include"iostream"
#include"cstdio"
#include"cstring"
#define N 10010

using namespace std;

int data[N];
int n;

void quicksort(int left,int right)
{
	if(left>=right) return ;
	else
	{
		int i=left;
		int j=right;
		int temp=data[left];
		while(i!=j)
		{
			while(i<j&&data[j]>=temp) j--;
			while(i<j&&data[i]<=temp) i++;
			if(i!=j)
			{
				int t=data[i];
				data[i]=data[j];
				data[j]=t;
			}
		}
		data[left]=data[i];
		data[i]=temp;
		quicksort(left,i-1);
		quicksort(i+1,right);
		return ;
	}
}

int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%d",&data[i]);
	quicksort(1,n);
	printf("%d\n",data[(n+1)/2]);
	return 0;
}

2.归并排序 700k 16Ms

#include"iostream"
#include"cstdio"
#include"cstring"
#define N 10010
#define inf 99999999

using namespace std;

int data[N];
int n;

void mergesort(int left,int mid,int right)
{
	int n1=mid-left+1;
	int n2=right-mid;
	int s1[n1+2];
	int s2[n2+2];
	int i,j;
	for(i=left;i<=mid;i++) s1[i-left+1]=data[i];
	for(j=mid+1;j<=right;j++) s2[j-mid]=data[j];
	i=j=1;
	s1[n1+1]=s2[n2+1]=inf;
	for(int k=left;k<=right;k++)
	{
		if(s1[i]>s2[j]) data[k]=s2[j++];
		else data[k]=s1[i++];
	} 
}

void merge(int left,int right)
{
	if(left>=right) return ;
	else
	{
		int mid=(left+right)/2;
		merge(left,mid);
		merge(mid+1,right);
		mergesort(left,mid,right);
	}
}

int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%d",&data[i]);
	merge(1,n);
	printf("%d\n",data[(n+1)/2]);
	return 0;
}

3.堆排 736k 16Ms

#include"iostream"
#include"cstdio"
#include"cstring"
#define N 10010

using namespace std;

int data[N];
int n;
int heap[N];
int heapnum;

void swap(int x,int y)
{
	int t=data[x];
	data[x]=data[y];
	data[y]=t;
}

void siftdown(int i)
{
	int t;
	while(i*2<=heapnum)
	{
		if(data[heap[i]]>data[heap[i*2]]) t=i*2;
		else t=i;
		if(i*2+1<=heapnum&&data[heap[i*2+1]]<data[heap[t]]) t=i*2+1;
		if(i!=t)
		{
			swap(i,t);
			i=t;
		}
		else break;
	}
}

void heapsort()
{
	for(int i=1;i<=n-1;i++)
	{
		swap(1,heapnum);
		heapnum--;
		siftdown(1);
	}
}

int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&data[i]);
		heap[i]=i;
	}
	heapnum=n;
	for(int i=n/2;i>=1;i--) siftdown(i);
	heapsort();
	printf("%d\n",data[(n+1)/2]);
	return 0;
}


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页