Last active
November 29, 2018 17:57
-
-
Save gilleyj/b5eb3349b797d62c95ab4884d6cebff8 to your computer and use it in GitHub Desktop.
C solution for merging two given *SORTED* arrays
This file contains hidden or 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
// | |
// solve the problem joel ... | |
// | |
// compile & test with: cc array_merge.c -o testit && testit | |
// | |
#include <stdio.h> | |
int main() { | |
// given two seperate arrays, return a sorted array in lowest time possible. | |
// assumption is that the two arrays are already independantly sorted | |
// time for this solution is t ~= n1 + n2 | |
// with out the assumption of structured data, this would need to be a merge sort at something like t >= n1 ^ n2 | |
// I chose not to do shortcuts in this for clarity, for example I would normally have written line 38 as: | |
// merge[walkmerge++] = aa[walka++]; | |
// set up the arrays to merge | |
int aa[] = {1, 3, 5, 7}; | |
int ab[] = {2, 4, 6, 8}; | |
// determing the length of arrays | |
int lena = sizeof(aa) / sizeof(aa[0]); | |
int lenb = sizeof(ab) / sizeof(ab[0]); | |
// allocate a new array for merge result | |
int merge[ lena+lenb ]; | |
// init some counters | |
int walka = 0, walkb = 0, walkmerge = 0; | |
// walk through both arrays with comparison to merge | |
while ( walka<lena && walkb<lenb ) { | |
// compare current element of array A to current element or array B | |
if (aa[walka] < ab[walkb]) { | |
// array A element is smaller, append to merge | |
merge[walkmerge] = aa[walka]; | |
// increment counter for merge and selected arrays | |
walka++; | |
walkmerge++; | |
} else { | |
// array B element is smaller (or equal), append to merge | |
merge[walkmerge] = ab[walkb]; | |
// increment counter for merge and selected arrays | |
walkb++; | |
walkmerge++; | |
} | |
} | |
// store remaining elements of array a | |
while ( walka<lena ) { | |
merge[walkmerge] = aa[walka]; | |
// increment counters | |
walka++; | |
walkmerge++; | |
} | |
// store remaining elements of array b | |
while ( walkb<lenb ) { | |
merge[walkmerge] = ab[walkb]; | |
// increment counters | |
walkb++; | |
walkmerge++; | |
} | |
// output merge | |
walkmerge = 0; | |
int lenmerge = sizeof(merge) / sizeof(merge[0]); | |
while ( walkmerge<lenmerge ) { | |
printf("%i, ", merge[walkmerge]); | |
walkmerge++; | |
} | |
printf("\n"); | |
return 0; | |
} | |
// I guess I got caught up in the fact that data is never so structured, next time pay attention to initial parameteres as given |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment