Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
|
Odd Even Sort implementation More...
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <inttypes.h>
Functions | |
void | swap (int32_t *first, int32_t *second) |
for assert | |
void | oddEvenSort (int *arr, int size) |
oddEvenSort sorts the array using the algorithm described above. | |
static void | test () |
Self-test implementations. | |
int | main () |
Main function. | |
Odd Even Sort implementation
This algorithm is divided into two phases- Odd and Even Phase. The algorithm runs until the array elements are sorted and in each iteration two phases occurs- Odd and Even Phases. In the odd phase, we perform a bubble sort on odd indexed elements and in the even phase, we perform a bubble sort on even indexed elements. Time Complexity: O(N ^ 2)
int main | ( | void | ) |
void oddEvenSort | ( | int * | arr, |
int | size | ||
) |
oddEvenSort sorts the array using the algorithm described above.
A boolean varaible(isSorted) is declared and initialised to "false". In the while loop, the variable(isSorted) is then set to "true". During even phase the for loop loops through the array, touching just the even indexes. i.e arr[0], arr[2], arr[4] and so on. While during the odd phase, the for loop loops through the array, touching just the odd indexes. i.e arr[1], arr[3], arr[5] and so on. During these phases, if the if statement check if the interger at the current position in the array is greater than the interger at the next array index (i.e arr[index + 2], to make sure the index is odd during the odd phase and even during the even phase). If the condition is true, the function "swap" is called and address of the intergers in question are passed as parameters. After the swap is completed, "isSorted" is set to "false". The while loop will keep running till the array is propertly sorted.
arr | array to be sorted |
size | the size of the array |
void swap | ( | int32_t * | first, |
int32_t * | second | ||
) |
for assert
for bool for IO operations for dynammic memory allocation for random number generation for int32_t types
Swap numbers by reference(using pointers)
first | pointer to first number |
second | pointer to second number |
|
static |
Self-test implementations.
Two tests (unsorted) arrays were created and their corresponding solution(sorted) arrays were also created. The test arrays and their respective sizes are then passed in to the oddEvenSort function. To test if the algorithm works, a for loop is assigned to loop through the both arrays(test and solution) and check if the array elements of the test array correspond to the elements of the solution array.