Merge two sorted one-dimensional arrays and keep the same sorting rules
1. Experimental purposes
Understanding the sequential representation and implementation of linear tables, and flexible use to solve more complex problems.
2. Content of experiment
Knowing that the two integer order tables are ordered, they are merged into an ordered order table.
Let's assume that two known arrays are LA= (3, 5, 8, 11), LB= (2, 6, 8, 9, 11, 15, 20), and are arranged in descending order.
Idea analysis:
First, you need to find a larger space to accommodate two arrays
If pointer operation is used, malloc () or realloc () function can be used to reapply for space size.
/*malloc()Function usage*/ #Include <stdlib.h>//Define header file void *malloc(int size); //Function declaration //Usage method //For example, allocate 100 storage spaces int *p; p = (int *)malloc( sizeof(int) *100); //Please refer to (Reprint) https://blog.csdn.net/linan5231/article/details/50930630 for details.
/* realloc()Function usage */ #include <stdio.h> void *realloc(); //Usage method //For example, change the original 100 spaces to 200 int *p; p = (int *)realloc( sizeof(int) *200); //For details, please refer to https://blog.csdn.net/vevenlcf/article/details/47036127.
Instead of pointing, we directly reapply a new array list[11] that can accommodate the original two arrays.
Then insert and sort the new array
As for insertion sort, you can see Introduction to Insert Sorting
Here is the code to implement this problem.
#include <stdio.h> int main() { int i, j, temp; int list_a[4]={3,5,8,11}, list_b[7]={2,6,8,9,11,15,20}; int list[11]={0}; //Output the original array data and merge it into a new, larger one-dimensional array printf("The original order was: \n"); printf("List A is: \n "); for(i=0;i<4;++i) { list[i]=list_a[i]; printf("%d ",list[i]); } printf("\nList B is: \n "); for(i=4;i<11;++i) { list[i]=list_b[i-4]; printf("%d ",list[i]); } //Select and sort new one-dimensional arrays for(i=1;i<11;++i) { temp=list[i]; j=i-1; while(j>=0 && list[j]>temp) { list[j+1]=list[j]; j=j-1; } list[j+1]=temp; } //Print out the results printf("\n\n\nThe combined sort is: \n "); for(i=0;i<11;++i) printf("%d ",list[i]); return 0; }
Of course, this problem can also be sorted by merging, and then posted after it has been written.
Welcome to provide better insights.