随机快速排序

#include "stdafx.h"
#include<iostream>
#include <stdlib.h> 
#include <time.h> 
using namespace std;

int RANDOM(int p, int r)
{
	srand((unsigned)time(NULL));
	return (rand() % (r - p + 1)) + p;
}

int partition(int a[], int p, int r) {
	int x, i,t;
	x = a[r];
	i = p - 1;
	t = 0;
	for (int j = p ; j <= r - 1; j++)
	{
		if (a[j]> x) 
		{
			i = i + 1;
			int ti;
			ti = a[i];
			a[i] = a[j];
			a[j] = ti;
 		}
		if (a[j] == x)
		{
			t = t + 1;
			int ti;
			ti = a[i+t];
			a[i+t] = a[j];
			a[j] = ti;
		}
	}
	int tii;
	tii = a[i+t+1];
	a[i+1+t] = a[r];
	a[r] = tii;
	if (i == r - 1)return (p + r) / 2;
	else 
	   return i+1;
}

bool equ(int a[], int p, int r)
{
	for (int i = p; i <= r; i++)
		if (a[i] != a[i + 1])return false;
	return true;
}
int random_partion(int a[], int p, int r)
{
	
	int i = RANDOM(p, r);
	int tii;
	tii = a[i];
	a[i] = a[r];
	a[r] = tii;
	return partition(a, p, r);
}


void quick(int a[], int p, int r) {
	if (p < r&&(!equ(a, p, r)))
	{
		int q = random_partion(a, p, r);
		quick(a, p, q - 1);
		quick(a, q+1, r);
	}
}
int main()
{
	int a[] = { 0, 1,1,1,1,1,1 };
	quick(a, 1, 6);
	for (int i = 1; i < 7; i++)
		cout << a[i];
	int b[] = { 0,3,3,2,5,3 };
	int q = partition(b, 1, 5);
	cout <<endl<< q;
	cout << RANDOM(1, 5);
	while (1);
    return 0;
}

  

posted @ 2017-03-17 22:35  lineaar  阅读(140)  评论(0编辑  收藏  举报