Last active
February 21, 2024 04:02
-
-
Save begeekmyfriend/c3896c675f4f081816620a6c6f5e9e88 to your computer and use it in GitHub Desktop.
Merge sort demo
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> | |
#include <stdlib.h> | |
static void show(int *nums, int lo, int hi) | |
{ | |
int i; | |
for (i = lo; i <= hi; i++) { | |
printf("%d ", nums[i]); | |
} | |
printf("\n"); | |
} | |
/* Merge two sorted array */ | |
static void merge(int *nums, int lo, int mid, int hi) | |
{ | |
int i, j, k, len = hi - mid; | |
int *tmp = malloc(len * sizeof(int)); | |
for (i = 0; i < len; i++) { | |
tmp[i] = nums[mid + 1 + i]; | |
} | |
i = mid; | |
j = len - 1; | |
k = hi; | |
while (i >= lo && j >= 0) { | |
if (nums[i] > tmp[j]) { | |
nums[k--] = nums[i--]; | |
} else { | |
nums[k--] = tmp[j--]; | |
} | |
} | |
while (j >= 0) { | |
nums[k--] = tmp[j--]; | |
} | |
free(tmp); | |
} | |
static void merge_sort(int *nums, int lo, int hi) | |
{ | |
if (lo >= hi) { | |
return; | |
} | |
int mid = lo + (hi - lo) / 2; | |
merge_sort(nums, lo, mid); | |
merge_sort(nums, mid + 1, hi); | |
merge(nums, lo, mid, hi); | |
} | |
int main(int argc, char **argv) | |
{ | |
int i, count = argc - 1; | |
int *nums = malloc(count * sizeof(int)); | |
for (i = 0; i < count; i++) { | |
nums[i] = atoi(argv[i + 1]); | |
} | |
merge_sort(nums, 0, count - 1); | |
show(nums, 0, count - 1); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment