Skip to content

Instantly share code, notes, and snippets.

@naezith
Last active January 4, 2016 11:34
Show Gist options
  • Save naezith/b19ebd8b84ce2b07618c to your computer and use it in GitHub Desktop.
Save naezith/b19ebd8b84ce2b07618c to your computer and use it in GitHub Desktop.
Merge two sorted arrays as a single sorted array
#include <stdio.h>
struct DynamicArray {
int* arr;
unsigned short size, cursor; //To track cursor's position
};
int main() {
struct DynamicArray arrays[3] = {NULL, 0, 0};
unsigned short i, j; //Loop counters
for (j = 0; j < 2; j++) {
//Taking the size
printf ("\nEnter the size of array %d : ", j + 1);
scanf ("%hu", &arrays[j].size);
//Dynamically allocate the memory for array with user-defined size
arrays[j].arr = (int*) calloc (arrays[j].size, sizeof (int));
arrays[2].size += arrays[j].size; //Third array's size will be sum of other two
//Taking elements
for (i = 0; i < arrays[j].size; i++) {
printf ("Enter the element %hu of array %hu : ", i + 1, j + 1);
scanf ("%d", &arrays[j].arr[i]);
}
}
//Create the third array
arrays[2].arr = (int*) calloc (arrays[2].size, sizeof (int));
//Loop trough the third array and pick the lowest numbers from other two arrays
for (i = 0; i < arrays[2].size; i++) {
//First array's element is smaller
if (arrays[0].cursor < arrays[0].size && arrays[0].arr[arrays[0].cursor] < arrays[1].arr[arrays[1].cursor]) {
arrays[2].arr[i] = arrays[0].arr[arrays[0].cursor];
arrays[0].cursor++; //increment the cursor position by 1
}
//Second array's element is smaller
else {
arrays[2].arr[i] = arrays[1].arr[arrays[1].cursor];
arrays[1].cursor++; //increment the cursor position by 1
}
printf ("\nThird array's element %hu is %d", i + 1, arrays[2].arr[i]);
}
//Exiting the program will free all memory on the heap so we don't need to use free() function in this program
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment