insertion Merge

/***
11.1
You are given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order.
***/
/**
IDEA: copy B to concat A. start from the head of B using insertion sort.
**/

#include<iostream>

using namespace std;

void exchange(int *a, int *b) {
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

int copyB2A(int *a, int szA, int *b, int szB) {
    int index = 0;
    int i = 0, j = 0;

    while(a[i] == 0) i++;

    if(i == szA) return 0;

    for(; i < szA; i++) {
        if(a[i] == 0) {
            if(index == 0) {
                index = i;
            }
            if(j < szB) {
                a[i] = b[j++];
            } else break;
        }
    }
    return index;
}

void merge(int *a, int index, int szB) {

    for(int i = index; i < szB + index; i++) {
        int j = i;
        while(a[j] < a[j-1]) {
            exchange(a+j, a+j-1);
            j--;
        }
    }
}

void main() {
    int a[] = {1, 3, 5, 7, 9, 0, 0, 0};
    int b[] = {2, 4, 6};
    int szA = sizeof(a) / sizeof(int);
    int szB = sizeof(b) / sizeof(int);
    int index;
    index = copyB2A(a, szA, b, szB);
    merge(a, index, szB);
    for(int i = 0; i < index + szB; i++)
        cout<<a[i]<<" ";
    cout << endl;

}

Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs