Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SleepSort.c #106

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions C/QuickSort.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Quick sort in C

#include <stdio.h>

void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}

int partition(int array[], int low, int high) {
int pivot = array[high];
int i = (low - 1);
for (int j = low; j < high; j++) {
if (array[j] <= pivot) {
i++;
swap(&array[i], &array[j]);
}
}
swap(&array[i + 1], &array[high]);
return (i + 1);
}

void quickSort(int array[], int low, int high) {
if (low < high) {
int pi = partition(array, low, high);
quickSort(array, low, pi - 1);
quickSort(array, pi + 1, high);
}
}

void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}

int main() {
int data[] = {8, 7, 2, 1, 0, 9, 6};
int n = sizeof(data) / sizeof(data[0]);
quickSort(data, 0, n - 1);

printf("Sorted array in ascending order: \n");
printArray(data, n);
}
30 changes: 30 additions & 0 deletions C/SleepSort.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// C implementation of Sleep Sort

#include <stdio.h>
#include <windows.h>
#include <process.h>

void routine(void *a)
{
int n = *(int *) a;
Sleep(n);
printf("%d ", n); // After the sleep, print the number
}

void sleepSort(int arr[], int n)
{
HANDLE threads[n];
for (int i = 0; i < n; i++)
threads[i] = (HANDLE)_beginthread(&routine, 0, &arr[i]);

WaitForMultipleObjects(n, threads, TRUE, INFINITE);
return;
}

int main()
{
int arr[] = {555, 32, 7, 888,37,2,52};
int n = sizeof(arr) / sizeof(arr[0]);
sleepSort (arr, n);
return(0);
}