#include "sort.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
#include <iostream>
using namespace std;
HANDLE nMutex;
DWORD WINAPI ThreadFunc1(LPVOID n); //冒泡排序
DWORD WINAPI ThreadFunc2(LPVOID n); //快速排序
int main( )
{
srand(time(NULL)); //初始化种子
for(int i=0;i<m;i++)
{
r1[i]=0;
r2[i]=0;
}
for(int i=0;i<m;i++)
{
r1[i]=rand()%1000;
}
cout<<"随机产生的数组为:"<<endl;
for(int i=0;i<m;i++)
{
cout<<r1[i]<<" ";
}
cout<<endl;
for(int i=0;i<m;i++)
r2[i]=r1[i];
HANDLE hTread1;
HANDLE hTread2;
hTread1=CreateThread(NULL,0,ThreadFunc1,NULL,0,NULL);//创建线程1
hTread2=CreateThread(NULL,0,ThreadFunc2,NULL,0,NULL);//创建线程2
nMutex=CreateMutex(NULL,FALSE,NULL);
CloseHandle(hTread1);
CloseHandle(hTread2);
Sleep(6000);
return 0;
}
/************************************************************************/
/* 线程1负责 冒泡排序
/************************************************************************/
DWORD WINAPI ThreadFunc1(LPVOID n)
{
bubblesort (r1,m);
cout<<"**************************************"<<endl;
cout<<"冒泡排序最后结果为:"<<endl;
cout<<"**************************************"<<endl;
for(int i=0;i<m;i++)
{
cout<<r1[i]<<" ";
}
cout<<endl;
cout<<"冒泡排序 结束"<<endl;
return 0;
}
/************************************************************************/
/* 线程2负责 快速排序 */
/************************************************************************/
DWORD WINAPI ThreadFunc2(LPVOID n)
{
quicksort(r2,0,m-1);
cout<<"**************************************"<<endl;
cout<<"快速排序最后结果为:"<<endl;
cout<<"**************************************"<<endl;
for(int i=0;i<m;i++)
{
cout<<r2[i]<<" ";
}
cout<<endl;
cout<<"快速排序 结束"<<endl;
cout<<"------------------------------------------------------"<<endl;
cout<<"------------------------------------------------------"<<endl;
return 0;
}
/************************************************************************/
/************************************************************************/
void bubblesort(int *r1,int m)
{
int i1,j1,exchange;
int temp;
for(i1=0;i1<=m-1;i1++)
{
exchange=0;
for(j1=m-1;j1>=i1;j1--)
{
if(r1[j1]<r1[j1-1])
{
WaitForSingleObject(nMutex,INFINITE);
Sleep(100);
temp=r1[j1];
r1[j1]=r1[j1-1];
r1[j1-1]=temp;
exchange=1;
count++;
cout<<"冒泡排序第"<<count<<"步后的结果:"<<endl;
for(int k1=0;k1<m;k1++)
{
cout<<r1[k1]<<" ";
}
cout<<endl;
ReleaseMutex(nMutex);
}
}
if(exchange==0) return;
}
}
void quicksort(int *r2,int s,int t)
{
int i=s,j=t;
int temp;
if(s<t)
{
temp=r2[s];
while(i!=j)
{
while(j>i&&r2[j]>=temp)
j--;
while(i<j&&r2[i]<=temp)
i++;
int x=r2[i];
r2[i]=r2[j];
r2[j]=x;
}
r2[s]=r2[j];
r2[i]=temp;
count1++;
WaitForSingleObject(nMutex,INFINITE);
Sleep(100);
cout<<"快速排序第"<<count1<<"步后的结果:"<<endl;
for(int k=0;k<m;k++)
{
cout<<r2[k]<<" ";
}
cout<<endl;
ReleaseMutex(nMutex);
quicksort(r2,s,j-1);
quicksort(r2,j+1,t);
}
}