c++11 版多线程 快速排序

// First.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <iterator>
#include <ctime>
#include <random>
#include <thread>
#include <mutex>
#include <memory>
using namespace std;
/** @ return the position of x  */
int partition(int arr[], int beg, int end){   /**  0,1,2,3,...,end*/
	int ramdom_index = rand() % (end - beg + 1) + beg;
	swap(arr[beg], arr[end]);
	int x = arr[beg];
	size_t i = beg + 1;
	for (size_t j = beg + 1; j <= end; j++){
		if (arr[j] < x)
			swap(arr[i++], arr[j]);
	}
	swap(arr[beg], arr[--i]);
	return i;
}

//void quickSort(int arr[], int beg, int end){
//	if (beg < end){
//		int mid = partition(arr, beg, end);
//		quickSort(arr, beg, mid - 1);
//		quickSort(arr, mid + 1, end);
//
//	}
//	/** return if(beg >= end) */
//}
size_t size = 10000000;
const int minSizeOfPerThread = 100000;
static int threadNum = 0;
mutex mu;
void quickSort(int arr[], int beg, int end){
	if (beg < end){
		int mid = partition(arr, beg, end);
		if (mid - beg > minSizeOfPerThread){
			thread thr1(quickSort, ref(arr), beg, mid - 1);
			thread thr2(quickSort, ref(arr), mid + 1, end);
			thr1.join();
			thr2.join();
			lock_guard<mutex>muguard(mu);
			threadNum += 2;
		}
		else
		{
			quickSort(ref(arr), beg, mid - 1);
			quickSort(ref(arr), mid + 1, end);

		}
	}

	/** return if(beg >= end) */

}


void test(){
	unique_ptr<int[]>testArr0(new int[size]);
	for (size_t i = 0; i < size; ++i)
		testArr0[i] = rand();

	time_t timeStart = clock();
	quickSort(testArr0.get(), 0, size - 1);
	time_t timeEnd = clock();

	cout << "sort time is " << (timeEnd - timeStart) << endl;

	/*for (size_t i = 0; i < size; ++i)
		cout << testArr0[i] << " ";
	*/cout << "test over\n" << endl;
	cout << "threadNum Is " << threadNum << endl;


}

void test2(){
	unique_ptr<int[]>testArr0(new int[size]);
	for (size_t i = 0; i < size; ++i)
		testArr0[i] = rand();
	time_t timeStart = clock();
	sort(testArr0.get(), testArr0.get() + size - 1);
	time_t timeEnd = clock();
	cout << "sort time is " << (timeEnd - timeStart) << endl;


	
	/*for (size_t i = 0; i < size; ++i)
	cout << testArr0[i] << " ";
	*/cout << "test over\n" << endl;

}
int _tmain(int argc, _TCHAR* argv[])
{
	test();
	test2();
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值