快速排序 (解决小划分文件)

#include<iostream>
#include<cstdlib>
#define M 20
using namespace std;
static int count_insert = 0;
static int count_partion = 0;

void swap(int& small, int& big)
{
	int temp = small;
	small = big;
	big = temp;
}
/*
|简述下插入排序:
|
|cur = 1 ->  right 为待排序部分,pre代表已排序部分。
|
|先把当先位置元素arr[cur]存入tmp,然后比较arr[pre]和arr[cur],
|如果待排序部分arr[cur] < arr[pre],则arr[pre + 1] = arr[pre]移位
|移位的目的是把较小的元素,这里是arr[cur]放入到已排序部分适当的位置
|这样每次arr[cur]都会被arr[pre]所覆盖,这也就是为什么刚开始tmp = arr[cur]的原因
|然后把tmp放置到arr[pre]位置处
*/
void insert_sort( int arr[], int left, int right)
{
	int tmp, cur , pre;
	for (cur = 1; cur < right; cur++)
	{
		pre = cur - 1;
		tmp = arr[cur];

		while ( tmp < arr[pre] && pre >= 0)
		{
			arr[pre + 1] = arr[pre];
			pre--;
		}
		arr[pre] = tmp;
	}
	count_insert += 1;
}

int partion(int arr[], int left, int right)
{
	int base = arr[right];
	int i = left -1;
	for( int j = left; j < right; j++)
	{
		if ( arr[j] < base )
		{
			i += 1;
			if ( arr[j] != arr[i])
				swap(arr[j], arr[i]);
		}
	}
	swap(arr[right], arr[i+1]);
	count_partion += 1;
	return i+1;
}

/*
| 如果划分后子文件的长度小于20,则用插入排序,
|否则快速排序
*/
void quick_sort(int arr[], int left, int right)
{
	if ( left < right )
	{
		if ( (right - left) <= M )
			insert_sort(arr, left, right);
		else
		{
			int sec = partion(arr, left, right);
			quick_sort(arr, left, sec - 1 );
			quick_sort(arr, sec + 1, right);
		}
	}
}

int main()
{
	
	const int size = 500;
	int s[size];
	srand(0);
	for (int i = 0; i < size; i++)
		s[i] = rand()%200;

	quick_sort(s, 0, size-1);

	for (i = 0; i < size; i++)
		cout << s[i] << " ";
	cout << endl;
	cout << "call insert_sort  " << count_insert << " times" <<endl;
	cout << "call partion_sort  " << count_partion << " times" <<endl;

	cin.get();

	return 0;
}

你可能感兴趣的:(快速排序)