Skip to content
Snippets Groups Projects
Commit 92921368 authored by azharfatrr's avatar azharfatrr
Browse files

rollback: returning serial merge sort in utils

parent add40387
No related merge requests found
...@@ -3,4 +3,4 @@ ...@@ -3,4 +3,4 @@
10114197 10114197
10323010 10323010
Runtime: 0.162644 s Runtime: 0.213774 s
...@@ -3,4 +3,4 @@ ...@@ -3,4 +3,4 @@
37739803 37739803
38222937 38222937
Runtime: 0.871782 s Runtime: 0.919108 s
...@@ -3,4 +3,4 @@ ...@@ -3,4 +3,4 @@
23198319 23198319
23380111 23380111
Runtime: 1.021110 s Runtime: 1.026466 s
...@@ -3,4 +3,4 @@ ...@@ -3,4 +3,4 @@
51451884 51451884
51774352 51774352
Runtime: 9.808481 s Runtime: 10.590979 s
...@@ -46,3 +46,61 @@ long get_floored_mean(int *n, int length) ...@@ -46,3 +46,61 @@ long get_floored_mean(int *n, int length)
return sum / length; return sum / length;
} }
/*
* Procedure merge_array
*
* Merges two subarrays of n with n[left..mid] and n[mid+1..right]
* to n itself, with n now ordered ascendingly
* */
void merge_array(int *n, int left, int mid, int right) {
int n_left = mid - left + 1;
int n_right = right - mid;
int iter_left = 0, iter_right = 0, iter_merged = left;
int *arr_left = (int *) malloc(n_left * sizeof(int));
int *arr_right = (int *) malloc(n_right * sizeof(int));
for (int i = 0; i < n_left; i++) {
arr_left[i] = n[i + left];
}
for (int i = 0; i < n_right; i++) {
arr_right[i] = n[i + mid + 1];
}
while (iter_left < n_left && iter_right < n_right) {
if (arr_left[iter_left] <= arr_right[iter_right]) {
n[iter_merged] = arr_left[iter_left++];
} else {
n[iter_merged] = arr_right[iter_right++];
}
iter_merged++;
}
while (iter_left < n_left) {
n[iter_merged++] = arr_left[iter_left++];
}
while (iter_right < n_right) {
n[iter_merged++] = arr_right[iter_right++];
}
free(arr_left);
free(arr_right);
}
/*
* Procedure merge_sort
*
* Sorts array n with merge sort algorithm
* */
void merge_sort(int *n, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
merge_sort(n, left, mid);
merge_sort(n, mid + 1, right);
merge_array(n, left, mid, right);
}
}
...@@ -26,4 +26,20 @@ int get_median(int *n, int length); ...@@ -26,4 +26,20 @@ int get_median(int *n, int length);
* */ * */
long get_floored_mean(int *n, int length); long get_floored_mean(int *n, int length);
/*
* Procedure merge_array
*
* Merges two subarrays of n with n[left..mid] and n[mid+1..right]
* to n itself, with n now ordered ascendingly
* */
void merge_array(int *n, int left, int mid, int right);
/*
* Procedure merge_sort
*
* Sorts array n with merge sort algorithm
* */
void merge_sort(int *n, int left, int right);
#endif #endif
\ No newline at end of file
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment