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

feat: add slow sort algorithm #1459

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
76 changes: 76 additions & 0 deletions sorting/slow_sort.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>

/*Displays array passed as parameter*/
void display(int arr[], int size)
{
for(int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}

printf("\n");
}

/*Swaps the two values passed to the function*/
void swap(int *num1, int *num2)
{
int temp = *num1;
*num1 = *num2;
*num2 = *num1;
}

/*
Slow sort function
@param arr The array to be sorted
@param low The starting index
@param high The ending index
*/
void slowsort(int arr[], int low, int high)
{
if (low >= high)
return;

int middle = (low + high) / 2;

slowsort(arr, low, middle);
slowsort(arr, middle+1, high);

if (arr[high] < arr[middle])
swap(&arr[high], &arr[middle]);

slowsort(arr, low, high - 1);
}

/*Test function*/
void test()
{
const int size = 20;

int *arr = (int *)calloc(size, sizeof(int));

for (int i = 0; i < size; i++)
{
arr[i] = rand() % 100;
}

slowsort(arr, 0, size-1);

for (int i = 0; i < size - 1; i++)
{
assert(arr[i] <= arr[i+1]);
}

display(arr, size);

free(arr);
}

int main()
{
srand(time(NULL));
test();
return 0;
}