睡眠排序–睡眠排序,确定性奇怪排序算法的另一个代表。
它的工作原理如下:
- 循环遍历元素列表
- 为每个循环启动一个单独的线程
- 线程休眠一段时间–元素值和睡眠后的值输出
- 循环结束时,等待线程最长的睡眠完成,显示排序后的列表
C 中睡眠排序算法的示例代码:
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
typedef struct {
int number;
} ThreadPayload;
void *sortNumber(void *args) {
ThreadPayload *payload = (ThreadPayload*) args;
const int number = payload->number;
free(payload);
usleep(number * 1000);
printf("%d ", number);
return NULL;
}
int main(int argc, char *argv[]) {
const int numbers[] = {2, 42, 1, 87, 7, 9, 5, 35};
const int length = sizeof(numbers) / sizeof(int);
int maximal = 0;
pthread_t maximalThreadID;
printf("Sorting: ");
for (int i = 0; i < length; i++) { pthread_t threadID; int number = numbers[i]; printf("%d ", number); ThreadPayload *payload = malloc(sizeof(ThreadPayload)); payload->number = number;
pthread_create(&threadID, NULL, sortNumber, (void *) payload);
if (maximal < number) {
maximal = number;
maximalThreadID = threadID;
}
}
printf("\n");
printf("Sorted: ");
pthread_join(maximalThreadID, NULL);
printf("\n");
return 0;
}
在此实现中,我在微秒上使用了 usleep 函数,其值乘以 1000,即以毫秒为单位。
算法的时间复杂度– O(很长)
链接
https://gitlab.com/demensdeum /algorithms/-/tree/master/sortAlgorithms/sleepSort
来源
https://codoholicconfessions.wordpress。 com/2017/05/21/strangest-sorting-algorithms/
https://twitter.com/javascriptdaily/status/856267407106682880?lang=en
https://stackoverflow.com/questions/6474318/what-is-the-time-complexity-of-the-sleep-sort