0
点赞
收藏
分享

微信扫一扫

C语言——快速排序_递归_非递归_效率比较

金穗_ec4b 2022-03-22 阅读 74

先看结果:

可见数据量大的时候,差距很明显。

原因:递归需要系统堆栈,空间消耗比非递归大,当递归深度较大时,可能会溢出。

递归的好处:代码易读,易写。

坏处:对空间消耗大,执行效率没循环高。

循环的好处:执行效率高。

坏处:有些算法,不易读,不易写。

总结一下就是:递归难为机器,循环难为人。

源码:

#include<iostream>
#include <time.h> 
#include <windows.h>
#include <stack>

using namespace std;

int Partition_1(int low, int high, int a[])
{
	a[0] = a[low];
	while (low<high)
	{
		while (low<high&&a[high]>=a[0])
		{
			--high;
		}
		a[low] = a[high];
		while (low < high && a[low] <= a[0])
		{
			++low;
		}
		a[high] = a[low];
	}
	a[low] = a[0];
	return low;
}

void QSort_1(int low, int high, int a[])
{
	int key=0;
	if (low < high)
	{
		key = Partition_1(low, high, a);
		QSort_1(low, key - 1, a);
		QSort_1(key + 1, high, a);
	}
}


int Partition_2(int low, int high, int b[])
{
	b[0] = b[low];
	while (low<high)
	{
		while (low < high && b[high] >= b[0])
		{
			high--;
		}
		b[low] = b[high];
		while (low < high && b[high] <= b[0])
		{
			low++;
		}
		b[high] = b[low];
	}
	b[low] = b[0];
	return low;
}

void QSort_2(int low, int high, int b[])
{
	stack<int> Stack;
	if (low < high)
	{
		int key = Partition_2(low, high,b);
		if (key-1>low)
		{
			Stack.push(low);
			Stack.push(key - 1);
		}
		if (key + 1 < high)
		{
			Stack.push(key + 1);
			Stack.push(high);
		}

		while (!Stack.empty())
		{
			low = Stack.top();
			Stack.pop();
			high = Stack.top();
			Stack.pop();

			key = Partition_2(low, high, b);
			if (key - 1 > low)
			{
				Stack.push(1);
				Stack.push(key - 1);
			}
			if (key + 1 < high)
			{
				Stack.push(key + 1);
				Stack.push(high);
			}
		}
	}
}

int main()
{
	int a[1000];//0号位为空 ,不参与排序
	int b[1000];//0号位为空 ,不参与排序
	for (int i = 999; i >= 1; i--)
	{
		a[i] = i;
		b[i] = i;
	}
	a[0] = 0;
	b[0] = 0;
	cout << "开始排序............." << endl;
	clock_t start_1,end_1;

	//递归排序
	start_1 = clock();
	for (int i = 0; i < 33333; i++)//测试数据=33333*999*999*3 约 一亿  
	{
		QSort_1(1, 999, a);
		QSort_1(999, 1, a);
		QSort_1(1, 999, a);
	}
	end_1 = clock();
	
	//非递归排序
	clock_t start_2, end_2;
	start_2 = clock();
	for (int i = 0; i < 33333; i++)
	{
		QSort_2(1, 999, a);
		QSort_2(999, 1, a);
		QSort_2(1, 999, a);
	}
	end_2 = clock();

	cout << "排序完成!" << endl;

	cout << "递归 time is :" << (end_1 - start_1) << "ms" << endl;
	cout << "非递归 time is :" << (end_2 - start_2) << "ms" << endl;
	if ((end_2 - start_2) < (end_1 - start_1))
		cout << "快速排序 非递归执行效率比递归高!" << endl;
	else if((end_2 - start_2) == (end_1 - start_1))
		cout << "快速排序 非递归执行效率比递归相等!" << endl;
	else
		cout << "快速排序 非递归执行效率比递归低!" << endl;
	cout << "在一亿数据测试 非递归 是递归 效率的:" << (double)((double)(end_1 - start_1) / (double)(end_2 - start_2)) << "倍!" << endl;

	int key = 0;
	cout << "输入1 查看排序结果" << endl;
	cin >> key;
	if (key == 1)
	{
		cout << "递归快速排序结果为:";
		for (int i = 1; i <= 999; i++)
			cout << a[i] << " ";
		cout << endl;
		cout << "非递归快速排序结果为:";
		for (int i = 1; i <= 999; i++)
			cout << b[i] << " ";
	}
	
	return 0;
}
举报

相关推荐

0 条评论