Mix two ordered int arrays to another ordered array and deduplicate them.
Question: place two ordered arrays a and B in the same Array c, so that c is also an ordered array (ascending) to remove repeated items.
The Code is as follows:
int merge_array (int *a , int *b, int *c, int n1, int n2){ if (n1 < 0 || n2 < 0) { return -1; } int i = 0; int j = 0; int k = 0; int count = 0; while (i < n1 && j < n2) { if (a[i] < b[j]) { if (k == 0) { c[k++] = a[i++]; count++; }else{ if (c[k-1] != a[i]) { c[k++] = a[i++]; count++; }else{ i++; } } }else if (a[i] == b[j]){ if (k == 0) { c[k++] = a[i++]; j++; count++; }else{ if (c[k-1] != a[i]) { c[k++] = a[i++]; j++; count++; }else{ i++; j++; } } }else{ if (k == 0) { c[k++] = b[j++]; count++; }else{ if (c[k-1] != b[j]) { c[k++] = b[j++]; count++; }else{ j++; } } } } while (i < n1) { if (k == 0) { c[k++] = a[i++]; count++; }else{ if (c[k-1] != a[i]) { c[k++] = a[i++]; count++; }else{ i++; } } } while (j < n2) { if (k == 0) { c[k++] = b[j++]; count++; }else{ if (c[k-1] != b[j]) { c[k++] = b[j++]; count++; }else{ j++; } } } return count;}
The test code is as follows:
int a[1] = {1}; int b[1] = {2}; int c[100] = {0}; int count = merge_array(a, b, c, 1, 01); for (int i = 0; i < count; i++) { printf("c[%d] : %d\n", i, c[i]); }
Tests are performed multiple times, including repeated items, 0 items, and negative items. The operation is correct. You are welcome to propose a better method!
Good night.
Non-deduplication:
void merge (int *a , int *b, int *c, int n1, int n2){ if (n1 < 0 || n2 < 0) { return; } int i = 0; int j = 0; int k = 0; while (i < n1 && j < n2) { if (a[i] < b[j]) { c[k++] = a[i++]; } else { c[k++] = b[j++]; } } while (i < n1) { c[k++] = a[i++]; } while (j < n2) { c[k++] = b[j++]; }}