您的位置:首页 > 编程语言 > C语言/C++

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

2014-08-18 16:36 218 查看
// 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: