sort.c: 多線程排序
? 主線程創建一個輔助線程
? 主線程使用選擇排序算法對數組的前半部分排序
? 輔助線程使用選擇排序算法對數組的后半部分排序
? 主線程等待輔助線程運行結束后,使用歸并排序算法歸并數組的前半部分和后半部分
實現思路:
ARRAY_COUNT
存放要進行排序的數字的個數,need_sort_array[ARRAY_COUNT]
;記錄待排序的數字,sorted[ARRAY_COUNT]
用來記錄歸并排序的結果。
副線程通過調用void *worker(void *arg)
函數實現對數組的前半部分的排序,采用插入排序實現,主線程,通過worker()
函數實現,同樣采用插入排序,最后的歸并排序通過Merge_array()
實現。
實現代碼:
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>#define ARRAY_COUNT 10
int need_sort_array[10]={5,7,8,5,24,25,67,33,1,55};
int sorted[10];void *worker(void *arg){int i,j;int tmp;int Min;for(i=0;i<ARRAY_COUNT/2;i++){Min=i;for(j=i+1;j<ARRAY_COUNT/2;j++){if(need_sort_array[Min]>need_sort_array[j])Min=j;}tmp=need_sort_array[i];need_sort_array[i]=need_sort_array[Min];need_sort_array[Min]=tmp;}
}void master(){int i,j;int tmp;int Min;for(i=ARRAY_COUNT/2;i<ARRAY_COUNT;i++){Min=i;for(j=i+1;j<ARRAY_COUNT;j++){if(need_sort_array[Min]>need_sort_array[j])Min=j;}tmp=need_sort_array[i];need_sort_array[i]=need_sort_array[Min];need_sort_array[Min]=tmp;}
}void Merge_Array(){int i=0,j=ARRAY_COUNT/2,k=0;while(i<ARRAY_COUNT/2&&j<ARRAY_COUNT){if(need_sort_array[i]<need_sort_array[j])sorted[k++]=need_sort_array[i++];elsesorted[k++]=need_sort_array[j++];}while(i<ARRAY_COUNT/2)sorted[k++]=need_sort_array[i++];while(j<ARRAY_COUNT)sorted[k++]=need_sort_array[j++];
}void print(int *array){int i;for(i=0;i<ARRAY_COUNT;i++)printf("%d ",array[i]);printf("\n");
}int main(){pthread_t pid;printf("Before sort,need_sort_array: ");print(need_sort_array);pthread_create(&pid,NULL,&worker,NULL);master();pthread_join(pid,NULL);printf("After sorted,need_sort_array: ");print(need_sort_array);Merge_Array();printf("sorted array: ");print(sorted);return 0;
}
歡迎留言交流。。。