Skip to content

Instantly share code, notes, and snippets.

@keithnorm
Created March 28, 2014 16:06
Show Gist options
  • Save keithnorm/9836363 to your computer and use it in GitHub Desktop.
Save keithnorm/9836363 to your computer and use it in GitHub Desktop.
k-way merge on 2D array of sorted arrays using bottom up mergesort
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void merge(int **a, int start, int end, int sz) {
int *a1 = a[start];
int *a2 = a[end];
int res[sz];
int i = 0;
int j = 0;
int idx = 0;
while (i < sz / 2 && j < sz / 2) {
if (a1[i] < a2[j]) {
res[idx++] = a1[i++];
} else {
res[idx++] = a2[j++];
}
}
while (i < sz / 2) {
res[idx++] = a1[i++];
}
while (j < sz / 2) {
res[idx++] = a2[j++];
}
idx--;
while (idx >= 0) {
a[start][idx] = res[idx];
idx--;
}
}
int main(int argc, const char * argv[])
{
int k = 4;
int n = 4;
int **a = (int**) malloc(sizeof (int*) * k);
for (int i = 0; i < k; i++) {
a[i] = (int*) malloc (sizeof (int) * n);
memset(a[i], 0, sizeof(int));
}
a[0][0] = 1;
a[0][1] = 24;
a[0][2] = 47;
a[0][3] = 54;
a[1][0] = 5;
a[1][1] = 6;
a[1][2] = 12;
a[1][3] = 14;
a[2][0] = 9;
a[2][1] = 10;
a[2][2] = 11;
a[2][3] = 18;
a[3][0] = 13;
a[3][1] = 16;
a[3][2] = 19;
a[3][3] = 23;
for (int i = 1; i < k; i *= 2) {
for (int lo = 0; lo < n - i; lo += i * 2) {
merge(a, lo, lo + i, n * i * 2);
}
}
for (int i = 0; i < k * n; i++) {
printf("%d", a[0][i]);
if (i < (k * n - 1)) {
printf(", ");
}
}
printf("\n");
free(a);
return 0;
}
Copy link

ghost commented Sep 15, 2021

code lỗi cũng đăng, mày bị ngu à

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment