-
Notifications
You must be signed in to change notification settings - Fork 307
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #111 from harjot3200/master
Sleep sort for an array for #3
- Loading branch information
Showing
1 changed file
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
#include <stdio.h> | ||
#include <windows.h> | ||
#include <process.h> | ||
|
||
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); | ||
} |