Merge two sorted integer arrays A and B into a new array (merge sort)

Merge sort : Divide the problem into small problems and solve them recursively , merging the answers obtained in the divided stages together.
Combines two sorted arrays into one, gives A=[1,2,3,4], B=[2,4,5,6], returns [1,2,2,3,4,4, 5,6].
Problem-solving idea: Compare the numbers in the two arrays from the beginning, take out the smaller one and store it in a new array in turn, until one of them is all compared, and store the rest of the other array directly into the new array.

vector<int> mergeSortedArray(vector<int> &A, vector<int> &B) {
        int i=0,j=0;
        std::vector<int>c;      
        while(i<A.size()&&j<B.size()){
            if(A[i]<B[j])
                c.push_back(A[i++]);
            else
                c.push_back(B[j++]);
        }
        while(i<A.size()){
            c.push_back(A[i++]);
        }
        while(j<B.size()){
            c.push_back(B[j++]);
        }
        return c;
    }

Sort an out-of-order
array Merge sort: Divide the problem into smaller problems and solve them recursively , merging the answers obtained in the divided stages together.
Divide the out-of-order array into two groups A and B. If the data in these two groups are all ordered, then the two groups of data can be easily sorted.
Sort A and B. When the divided group has only one data (the data length is 1, that is, the starting subscript of the data is equal to the ending subscript), it can be considered that the group has achieved order.

public static void sort(int []arr){
        int []temp = new int[arr.length];//在排序前,先建好一个长度等于原数组长度的临时数组,避免递归中频繁开辟空间
        sort(arr,0,arr.length-1,temp);
    }
    private static void sort(int[] arr,int left,int right,int []temp){
        if(left<right){
            int mid = (left+right)/2;
            sort(arr,left,mid,temp);//左边归并排序,使得左子序列有序
            sort(arr,mid+1,right,temp);//右边归并排序,使得右子序列有序
            merge(arr,left,mid,right,temp);//将两个有序子数组合并操作
        }
    }
    private static void merge(int[] arr,int left,int mid,int right,int[] temp){
        int i = left;//左序列指针
        int j = mid+1;//右序列指针
        int t = 0;//临时数组指针
        while (i<=mid && j<=right){
            if(arr[i]<=arr[j]){
                temp[t++] = arr[i++];
            }else {
                temp[t++] = arr[j++];
            }
        }
        while(i<=mid){//将左边剩余元素填充进temp中
            temp[t++] = arr[i++];
        }
        while(j<=right){//将右序列剩余元素填充进temp中
            temp[t++] = arr[j++];
        }
        t = 0;
        //将temp中的元素全部拷贝到原数组中
        while(left <= right){
            arr[left++] = temp[t++];
        }
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325521675&siteId=291194637