qfedu-linux-advanced-level/day6/homework/h7.c

84 lines
2.1 KiB
C
Raw Normal View History

2023-08-21 22:01:14 +08:00
/*
线线
线
*/
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
typedef struct array_s
{
int *arr; // 数组元素头指针
int start_pos; // 起始位置
int end_pos; // 结束位置
} ARRAY;
void *sort(void *data)
{
ARRAY *array = (ARRAY *)data;
for (int i = array->start_pos; i < array->end_pos; i++)
{
for (int j = array->start_pos; j < array->end_pos - i; j++)
{
if (array->arr[j] > array->arr[j + 1])
{
array->arr[j] ^= array->arr[j + 1];
array->arr[j + 1] ^= array->arr[j];
array->arr[j] ^= array->arr[j + 1];
}
}
}
return NULL;
}
int main()
{
int arr[9] = {1, 4, 2, 9, 0, 5, 6, 1, 8};
ARRAY array1 = {arr, 0, 2};
ARRAY array2 = {arr, 3, 5};
ARRAY array3 = {arr, 6, 8};
pthread_t t1, t2, t3;
pthread_create(&t1, NULL, sort, &array1);
pthread_create(&t2, NULL, sort, &array2);
pthread_create(&t3, NULL, sort, &array3);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
// 合并排序结果
int merged[9];
int i = 0;
for (int j = array1.start_pos; j <= array1.end_pos; j++)
{
merged[i++] = arr[j];
}
for (int j = array2.start_pos; j <= array2.end_pos; j++)
{
merged[i++] = arr[j];
}
for (int j = array3.start_pos; j <= array3.end_pos; j++)
{
merged[i++] = arr[j];
}
// 创建数组结构和新线程,将合并后的数组进行排序
ARRAY arr4 = {merged, 0, 8};
pthread_t t4;
pthread_create(&t4, NULL, sort, &arr4);
pthread_join(t4, NULL);
// 输出排序结果
printf("排序后的数组:");
for (int i = 0; i < 9; i++)
{
printf("%d ", merged[i]);
}
printf("\n");
return 0;
}