0

I was wondering if anybody had any idea of how to quickly braid two arrays into one? Lets say there are two arrays like this:

String [ ] a1 = {"b","d","i","j","p","w","z"} 

String [ ] a2 = {"a","c","e","f","h","q","r"}. 

These are both sorted, but I want to merge them with a braiding technique, so that it'll become one long sorted array.

This is my method so far, and it does not work, the tmp array ends up with just null at it [x].

static void braid(String [] a, String[] b){
    String [] tmp = new String [a.length+b.length];
    for(int i = 0; i < a.length; i++){
        for(int j = 0; j < b.length; j++){
            if(a[i].compareTo(b[j]) < 0) tmp[i] = a[i];
            else if(b[i].compareTo(a[j]) < 0) tmp[i] = b[i];
        }
    }
    for(int i = 0; i < tmp.length;i++){
        System.out.print(tmp[i] + "+");
    }
    System.out.println();
}
keenthinker
  • 7,645
  • 2
  • 35
  • 45

2 Answers2

1

I haven't heard of the term "braiding" before -- yet a solution to the problem itself is the following:

Iterate using a single while loop, keeping a position for both a1 and a2 (both starting at 0). The condition of the while loop should check if the positions for a1 and a2 do not grow larger than the size of a1 and a2, respectively. Within the while loop only increase the position for the array, from which you insert into tmp -- i.e. the one containing the smaller element.

user152468
  • 3,202
  • 6
  • 27
  • 57
0

I would import ArrayUtils class from the Apache commons library. Why reinvent the wheel when it already exits.

String[] a3 = ArrayUtils.addAll(a1, a2);
Arrays.sort(a3);
ndrone
  • 3,524
  • 2
  • 23
  • 37