Hey guys, my teacher for Computer Science AP told us to merge sort two already sorted arrays combined together.
The array given is:
{1,5,10,15,20,25,3,4,12,21,22}
Array section 1 starts at 0 and ends at 5.
Array section 2 starts at 6 and ends at 10.
basically we are to write a code that will sort the above into:
{1,3,4,5,10,12,15,20,21,22,25}
What I got so far
public int[] merge(int[] list, int a, int b, int c){
//pre: a < b and a and b are within the array bounds
//post: returns a sorted array
int[] temp = new int[ list.length ];
//YOUR CODE TO MERGE
int pos1 = a;
int pos2 = b;
int dest = 0;
for (int i = 0; i< list.length; i++) { //filling temp
temp[i] = list[i];
}
while ( (dest < temp.length) || (pos1 < b) || (pos2 < c) ){ //conditions
if (temp[pos1] < temp[pos2]) {
temp[dest] = temp[pos1];
pos1++;
dest++;
}
else {
int temporary = temp[pos2]; //hold the value at pos2
for (int i = dest; i< pos2; i++) { //shift array one over
temp[i+1] = list[i];
}
temp[dest] = temporary; //put value at pos2
pos2++;
dest++;
for (int h = 0; h < list.length; h++) { //refill list
list[h] = temp[h];
}
}
}
return(temp);
}
The output I'm getting is basically 1 followed by all 3's. I know that somehow the 3 is getting shifted over too. However when I change where the array gets shifted, it still gives me the same printout.
