I'm writing a code that ask at the user to insert the numbers of the array and then write each numbers, do the same thing in another array, and at the end compare the first array with the second array and print out the bubble sort of all numbers, so a kind of bubble sort for the first and second array togheter. I wrote this below, but I don t know how to compare with one method the two different arrays.
public static void main(String[] args) {
public static int[] macello(int[]A){
for(int i=0; i<A.length-1; i++){
for(int j=0; j<A.length-1-i;j++){
if(A[j]>A[j+1]){
int temp = A[j+1];
A[j+1]= A[j];
A[j] = temp;
}
}
}
return A;
}
public static void printArray2(int[]A){
for(int i = 0; i<A.length; i++){
System.out.print(A[i]+",");
}
}
Scanner scan = new Scanner(System.in);
System.out.println("Insert the capacity's array1: ");
int n = scan.nextInt();
int[]numbers1 = {n};
for(int i=0; i<n; i++){
System.out.println("Insert the value of each numbers: ");
int j =0;
numbers1[j] = scan.nextInt();
j++;
}
System.out.println("Insert the capacity's array2: ");
int m = scan.nextInt();
int[]numbers2 = {m};
for(int i=0; i<m; i++){
System.out.println("Insert the value of each numbers: ");
int j=0;
numbers2[j] = scan.nextInt();
j++;
}
macello(Arrays.equals(numbers1,numbers2));
printArray2(Arrays.equals(numbers1,numbers2));
}
}
You mention in the comments that you've already solved bubblesort. So I'm going to assume you have a method with the signature
void bubbleSort(int[] arr)
.Your code shows you understand how to acquire an array from the user, so we don't need to handle that.
Now what you're describing is bubbleSorting these two arrays. To do this, you need one -big- array that holds them both.
Ideally you wrap that logic in a merge method - this particular method leverages the Arrays and System classes to do some of the lifting for you. Obviously you could use the "naive" logic above if you want.
If you also make a method that acquires an array, like this:
Then your code becomes very, very clean:
I made a driver to test each of these ideas out to make sure they all work. I am a bit concerned, though, because you mention recursion. As you can see in this driver, there is no recursion here. Also be aware that I take a number of shortcuts that are probably not allowed (such as
System.arraycopy
,Arrays.copyOf
, andArrays.toString
). I just wanted to validate the various pieces of functionality. The message uses 1 indexing because that's what most people think in. If you enter 5 elements, they'll be 1-5. You and I know Java stores them 0 indexed, 0-4. It's just a matter of taste and UX.And here's what I get when I run it