Last active
February 29, 2024 08:21
-
-
Save SrBlecaute01/90ab01447f8862e5c0447b204e648945 to your computer and use it in GitHub Desktop.
Implementation of the merge sort algorithm in C
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
#include <stdio.h> | |
void merge(int* input, int left, int middle, int right) { | |
// variables for indices in loops | |
// z is used to keep the input index | |
int i, j, z = left; | |
// calculating the lenght of the copy array | |
int lenght = right - left + 1; | |
// creating the copy array | |
int copy[lenght]; | |
// copying the input array to the copy array | |
for (i = 0; i < lenght; i++) { | |
// considering the left index to copy the array | |
copy[i] = input[left + i]; | |
} | |
// calculating the copy left index | |
int copyLeft = middle - left + 1; | |
// calculating the copy right index | |
int copyRight = right - middle; | |
// comparing the elements of the copy array and sorting them | |
for (i = 0, j = 0; i < copyLeft && j < copyRight; z++) { | |
// comparing left and right of the copy | |
if (copy[i] <= copy[copyLeft + j]) { | |
// adding left element to input | |
input[z] = copy[i++]; | |
continue; | |
} | |
// adding right element to input | |
input[z] = copy[copyLeft + j++]; | |
} | |
// adding the remaining elements to the input array | |
while (i < copyLeft) input[z++] = copy[i++]; | |
while (j < copyRight) input[z++] = copy[copyLeft + j++]; | |
} | |
void sort(int* input, int left, int right) { | |
// If the left index is greater than or equal to the right index, the sort is complete | |
if (left >= right) return; | |
// Calculating the middle index | |
int middle = (left + right) / 2; | |
// recusirve merge function to sort of the left at the middle of the array | |
sort(input, left, middle); | |
// recusirve merge function to sort of the middle at the right of the array | |
sort(input, middle + 1, right); | |
// Check if the array is already sorted | |
if (input[middle] <= input[middle + 1]) return; | |
// merge the array | |
merge(input, left, middle, right); | |
} | |
void mergeSort(int* input, int lenght) { | |
// calling the sort function | |
sort(input,0, lenght - 1); | |
} | |
int main() { | |
int array[] = {38, 27, 43, 3, 9, 82, 10, 20, 100, 1, 2, 4, 3, 5, 77}; | |
int lenght = sizeof(array) / sizeof(array[0]); | |
mergeSort(array, lenght); | |
for (int i = 0; i < lenght; i++) { | |
printf("%d ", array[i]); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment