Reputation: 23
I have just have written this code I want it to merge two Arrays in one and sort it .. I have changed a lot of the code , I think my error is in the method array_intil()... but I can't find it...thanks all
public class Test3 {
public int [] array_erz(int[]A1,int[]A2){
int []neu=new int[A1.length+A2.length];
return neu;
}
public void swap(int[]values,int i,int k){
int temp;
temp=values[i];
values[i]=values[k];
values[k]=temp;
}
public int [] array_intil(int [] neu,int[]A1,int []A2){
for (int i=0;i<A1.length;i++){
neu[i]=A1[i];
for (int k=A1.length;k<neu.length;k++){
neu[k]=A2[i];
}}
return neu;
}
public int[] sort(int[] neu){
for (int i=0;i<neu.length;i++){
for (int k=neu.length-1;k>i;k--){
if (neu[i]>neu[k]){
swap(neu,i,k);
}
}
}
return neu;
}
public static void main (String[]args){
int [] A1={7,0,12,738};
int []A2={14,105,2,13,404,1,15,130};
Test3 t=new Test3();
int [] A3=t.array_erz(A1, A2);
t.array_intil(A3, A1, A2);
t.sort(A3);
for (int i=0;i<A3.length;i++){
System.out.print(A3[i]+",");
}
}
}
The result in the console is: 0,7,12,13,13,13,13,13,13,13,13,738,
Upvotes: 0
Views: 75
Reputation: 1520
you are right there is problem in your array_intil method. In your program , the second for loop get executed for every iteration of first loop
modify your method as below:
public int [] array_intil(int [] neu,int[]A1,int []A2){
int i=0;
for (i=0;i<A1.length;i++){
neu[i]=A1[i];
}
int m=0;
for (i=A1.length;i<neu.length;i++){
neu[i]=A2[m];
m++;
}
return neu;
}
Now correct/modify your sorting/swapping algo.
Upvotes: 0
Reputation: 11440
You had a nested loop adding A2 lots of times, try the following change:
public int [] array_intil(int [] neu,int[]A1,int []A2){
for (int i=0;i<A1.length;i++){
neu[i]=A1[i];
}
for (int k=A1.length;k<neu.length;k++){
neu[k]=A2[k-A1.length];
}
return neu;
}
Also always keep your code well formatted with tabs, I almost missed the nested for loop cause they were indented the same!
Upvotes: 1