多线程暖手宝

本文通过实现快速排序和冒泡排序算法,并采用多线程的方式进行比较。使用C++编程语言,在同一数据集上分别运行两种排序算法,记录并展示它们的执行时间差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<sys/time.h>
#include<pthread.h>
using namespace std;

template<class T>
void quick_sort(T a[], int low, int high)
{
    int first = low;
    int last = high;
    int key = a[first];
    
    if(low >= high)
        return;
    while(first < last)
    {
        while(first < last && a[last] >= key)last--;
        a[first] = a[last];
        
        while(first < last && a[first] <= key)first++;
        a[last] = a[first];
    }
    a[first] = key;
    quick_sort(a, low, first - 1);
    quick_sort(a, first + 1, high);
}

#define CONST_ARRAY_SIZE (100000)

template<class T>
void bubble_sort(T a[], int n)
{
    for(int j = 0; j < n - 1; j++)
        for(int i = 0; i < n - 1 - j; i++)
            if(a[i] > a[i + 1])
                swap(a[i], a[i + 1]);
}

void* call_bubble_sort_process(void* args)
{
    struct timeval start, end;
    
    int *pIntArray = (int*)malloc(CONST_ARRAY_SIZE*sizeof(int));
    for(int i = 0; i < CONST_ARRAY_SIZE; i++)
        pIntArray[i] = CONST_ARRAY_SIZE - i;
    
    gettimeofday(&start, NULL);
    //quick_sort(pIntArray, 0, CONST_ARRAY_SIZE - 1);
    bubble_sort(pIntArray, CONST_ARRAY_SIZE);
    gettimeofday(&end, NULL);
    
    for(int j = 0; j < 10; j++)
        cout<<pIntArray[j]<<" ";
    cout<<endl;
    
    cout<<"waste time = "<<(end.tv_sec - start.tv_sec)<<"s"<<(end.tv_usec - start.tv_usec)<<"us"<<endl;
    
    free(pIntArray);
    return NULL;
}

#define PROCESS_NUM (8)
void start_thread()
{
    pthread_t th[PROCESS_NUM];
    
    for(int i = 0; i < PROCESS_NUM; i++)
        pthread_create(&th[i], NULL, call_bubble_sort_process, NULL);
    
    for(int i = 0; i < PROCESS_NUM; i++)
        pthread_join(th[i], NULL);
    
}

int main()
{
    start_thread();

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值