快速排序 O(nlogn)

#include<bits/stdc++.h>
using namespace std;
int a[200],n;
void q_sort(int l,int r){
	if(l>r)
	return;
	int i=l,j=r,md,t;
	md=a[l];
	while(i!=j){
		while(a[j]>=md&&i<j) 
		j--;
		while(a[i]<=md&&i<j)
		i++;
		if(i<j)
		{
			t=a[i];
			a[i]=a[j];
			a[j]=t;
		}
	}
          a[l]=a[i];
          a[i]=md;
          q_sort(l,i-1);
          q_sort(i+1,r);
}
int main(){
	int i;
	while(cin>>n){
		for(i=0;i<n;i++)
		cin>>a[i];
		q_sort(0,n-1);
		for(i=0;i<n;i++)
		cout<<a[i]<<' ';
		cout<<endl;
	}
	return 0;
}
其实非递归就是把需要递归的左右边界记录就好了
#include<iostream>
using namespace std;

struct lr{
	int l,r;
};

const int N = 1e3 + 10;
int a[N];

void q_sort(int *a,int L,int R)
{
	lr t[N];
	int cur = 1;
	t[cur].l = L,t[cur].r = R;
	
	while(cur)
	{
		int last = cur;
		int up = t[cur].r,down = t[cur].l;
		//cout << down << " "  << up << endl;
		cur--;
		
		int temp = a[down];
		while(down < up)
		{
			while(a[up] >= temp && up > down)
			--up;
			while(a[down] <= temp && up > down)
			++down;
			
			if(down < up)
			{
				int na = a[down];
				a[down] = a[up];
				a[up] = na;
			}
		}
		
		a[t[last].l] = a[down];
		a[down] = temp;
		
		if(down - 1 > t[last].l)
		{
			cur++;
			t[cur].l = t[last].l;
			t[cur].r = down - 1;
		}
		
		if(down + 1 < t[last].r)
		{
			cur++;
		    t[cur].l = down + 1;
			t[cur].r = t[last].r;
		}
	}
}

int main()
{
	int n;
	while(cin >> n)
	{
		for(int i = 1;i <= n;i++)
		cin >> a[i];
		q_sort(a,1,n);
		
		for(int i = 1;i <= n;i++)
		cout << a[i] << " \n"[i == n]; 
	}
	return 0;
}
posted @ 2018-08-16 14:51  ChunhaoMo  阅读(296)  评论(0)    收藏  举报