亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

請問該如何利用pthread實現快速排列(qsort) ?

請問該如何利用pthread實現快速排列(qsort) ?

皈依舞 2022-07-15 14:10:58
qsort頭文件已經給出了,該如何實現快速排列(qsort)?
查看完整描述

3 回答

?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

struct sortdata //存放線程的函數mysort的數據
{
int a[10];
int n;
}mydata;
void *mysort(void * data)
{
sort(data->a, data->n); //qsort 里面的sort函數。
return 0;
}
void myexit() //按任意鍵退出?;蛘唠S便來個別的功能也一樣。多線程嘛。
{
getchar();
}

int main()
{
int a[10] = {5, 3, 1, 2, 7, 9, 6, 8, 4, 0};
pthread_t t1;
mydata.n = 10;
mydata.a = a;
if(pthread_create(&t1, NULL, mysort, (void*)&data))
perror("thread create failed.\n");
myexit(0);
return 0;
}
我也不知道你qsort的參數是什么。大概就這意思,樓主能看明白吧。代碼純手打,不過沒運行過,你試試吧。
大概意思就是2個函數并行執行,一邊查看你是否有輸入,一邊排序,如果你數組夠大的話,比如100000,可能更加明白。你按一下任意鍵 馬上就強制退出不sort了。


查看完整回答
反對 回復 2022-07-18
?
蕪湖不蕪

TA貢獻1796條經驗 獲得超7個贊

你好#include"stdafx.h"
/* QSORT.C: This program reads the command-line
* parameters and uses qsort to sort them. It
* then displays the sorted arguments.
*/
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
int compare( const void *arg1, const void *arg2 );
void main( int argc, char **argv )
{
char a[255]="1723649\0";
int k=strlen(a);
qsort((void *)a,(size_t)strlen(a),sizeof(char),compare);
printf ("%s",a);
}
int compare( const void *arg1, const void *arg2 )
{
return -(((char *)arg1)[0]-((char*)arg2)[0]);//降序,這個值取負則為升序



查看完整回答
反對 回復 2022-07-18
?
收到一只叮咚

TA貢獻1821條經驗 獲得超5個贊

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
/*定義排序工作線程函數參數結構體*/
typedef struct _qsort_parm
{
int *array;
int low;
int high;

} qsort_parm_t;
/*分段*/
int partition(int *array,int low, int high)
{
int pivot = *(array + low);
while (low < high)
{
while ( low < high && array[high] >= pivot)
{
high--;
}
*(array + low) = *(array + high);
while(low < high && array[low] <= pivot)
{
low++;
}
*(array + high) = *(array + low);
}
*(array + low) = pivot;
return low;
}
/*線程執行函數*/
void *quicksort_worker (void *parm)
{
pthread_t corpid;
qsort_parm_t *iparm = (qsort_parm_t *) parm;
int keypos = 0;
qsort_parm_t qparm;
void *ret;

if (iparm->low < iparm->high)
{
/*分段*/
keypos = partition(iparm->array,iparm->low,iparm->high);
qparm.array = iparm->array;
qparm.low = iparm->low;
qparm.high = keypos - 1;
/*創建子線程處理前半段*/
pthread_create(&corpid,NULL,quicksort_worker,&qparm);
iparm->low = keypos + 1;
/*本線程處理后半段*/
quicksort_worker(iparm);
/*等待子線程結束*/
pthread_join(corpid,&ret);
}
}

void quicksort_multithread(int *pA,int low,int high)
{
qsort_parm_t qparm;
qparm.array = pA;
qparm.low = low;
qparm.high = high;
quicksort_worker(&qparm);
}

int main (void){
int array[20] = {9,8,0,1,4,7,6,2,3,5,19,11,18,16,10,22,38,45,14,21};
int i = 0;
quicksort_multithread(array,0,19);
for (i = 0;i < 20;i ++)
{
printf ("%d ",array[i]);
}
return 0;
}


查看完整回答
反對 回復 2022-07-18
  • 3 回答
  • 0 關注
  • 203 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號