第2次实验——算法基本功 与 综合思考

(1)算法基本功——快速排序

    对文件 largeW.txt下载链接)中的数据,应用快速排序算法进行排序,并与冒泡排序、归并排序进行时间比较。体验算法复杂度对设计算法的影响。

代码如下:

#include <iostream>
#include <fstream>
#include <ctime> 
using namespace std;

#define SIZEOFARRAY 1000000

void exchange(int &a,int &b);
int partition(int A[] , int p,int r);
void QuickSort(int A[] , int p,int r);

int main ()
{
	ifstream inFile("largeW.txt");
	ofstream outFile("largeW_QuickSort.txt");
	if(!inFile || !outFile)
	{
		cout<<"读取或写入文件失败!"<<endl;
		inFile.close();
		outFile.close();
		return -1;
	}
	int *arrayToSort = new int[SIZEOFARRAY];
	int count = 0;
	while( !inFile.eof())  
			inFile>>arrayToSort[count++];

	clock_t start_time,end_time;  
	double totaltime;  
	start_time = clock();//记录开始时间
	
	QuickSort(arrayToSort ,0 ,SIZEOFARRAY-1);
	for (int i = 0; i != SIZEOFARRAY ;++i)
		outFile << arrayToSort[i] << endl;

	end_time = clock();//记录结束时间  
	totaltime=(double)(end_time-start_time)/CLOCKS_PER_SEC;  
	cout<<"\n此程序的运行时间为"<<totaltime<<"秒!"<<endl;  

	inFile.close();
	outFile.close();
	delete [] arrayToSort;
	return 0;
}

void exchange(int &a,int &b)
{
	int temp = a;
	a=b;
	b=temp;
}

int partition(int A[] , int p,int r)
{
	int x = A[r];
	int i = p-1;
	for (int j = p;j != r ;++j)
	{
		if(A[j] <= x)
		{
			i += 1;
			exchange(A[i],A[j]);
		}
	}
	exchange(A[i+1],A[r]);
	return i+1;
}

void QuickSort(int A[] , int p,int r)
{
	int q = 0;
	if(p<r)
	{
		q=partition( A ,p ,r );
		QuickSort(A ,p ,q-1);
		QuickSort(A ,q+1 ,r);
	}

}

结果如下:


对比前面的冒泡排序以及归并排序

冒泡排序:


归并排序:


可以看出来快速排序(O(nlogn))与归并排序(O(nlogn))的效率相差不多,也同时比冒泡排序(O(n2))的效率要高很多!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值