From 0f9b083ed786afcc0149d2380b158fadc01cbf83 Mon Sep 17 00:00:00 2001 From: harjot3200 Date: Sun, 8 Oct 2017 11:59:46 +0530 Subject: [PATCH] Sleep sort for an array --- Sorting Algorithms/sleep sort.c | 41 +++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Sorting Algorithms/sleep sort.c diff --git a/Sorting Algorithms/sleep sort.c b/Sorting Algorithms/sleep sort.c new file mode 100644 index 00000000..e0217ca2 --- /dev/null +++ b/Sorting Algorithms/sleep sort.c @@ -0,0 +1,41 @@ +#include +#include +#include + +void routine(void *a) +{ + int n = *(int *) a; // typecasting from void to int + + // Sleeping time is proportional to the number + // More precisely this thread sleep for 'n' milliseconds + Sleep(n); + + // After the sleep, print the number + printf("%d ", n); + +void sleepSort(int arr[], int n) +{ + // An array of threads, one for each of the elements + // in the input array + HANDLE threads[n]; + + // Create the threads for each of the input array elements + for (int i = 0; i < n; i++) + threads[i] = (HANDLE)_beginthread(&routine, 0, &arr[i]); + + // Process these threads + WaitForMultipleObjects(n, threads, TRUE, INFINITE); + return; +} + +// Driver program to test above functions +int main() +{ + // Doesn't work for negative numbers + int arr[] = {34, 23, 122, 9}; + int n = sizeof(arr) / sizeof(arr[0]); + + sleepSort (arr, n); + + return(0); +} \ No newline at end of file