The Java variable is a little weird

Asked 2 years ago, Updated 2 years ago, 18 views

import java.util.Random;

public class Compare {
    public static void main(String[] args) {
        int[] arr = new int[100];
        Random rand = new Random();

        for(int i = 0; i < arr.length; i++) {
            arr[i] = rand.nextInt(100) + 1;
        }

        int[] ascSortedArr = new int[100];
        ascSortedArr = ascBubbleSort(arr);
        int[] decSortedArr = new int[100];
        decSortedArr = decBubbleSort(arr);

        for(int j = 0; j < arr.length; j++) {
            System.out.println(ascSortedArr[j]);
        }
        for(int j = 0; j < arr.length; j++) {
            System.out.println(decSortedArr[j]);
        }
    }

    public static int[] ascBubbleSort(int[] arr) {
        for(int i = 0; i < arr.length; i++) {
            for(int j = 0; j < arr.length -1; j++) {
                int temp;

                if(arr[j] > arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }

        }

        return arr;
    }

    public static int[] decBubbleSort(int[] arr) {
        for(int i = 0; i < arr.length; i++) {
            for(int j = 0; j < arr.length -1; j++) {
                int temp;

                if(arr[j] < arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }

        }

        return arr;
    }
}

The output comes out as ascending and descending two times, but both come as descending. I don't know where the problem is.

java

2022-09-20 17:11

1 Answers

The array of java is passed as a reference. The code you created is sorted ascending and descending again for one array, so only descending results are output.

In other words, arr, ascSortedArr, decSortedArr are looking at the same arrangement.

If you change the order of output as shown below, it will be printed as intended.

        int[] ascSortedArr = new int[100];
        ascSortedArr = ascBubbleSort(arr);
        for(int j = 0; j < arr.length; j++) {
            System.out.println(ascSortedArr[j]);
        }
        int[] decSortedArr = new int[100];
        decSortedArr = decBubbleSort(arr);
        for(int j = 0; j < arr.length; j++) {
            System.out.println(decSortedArr[j]);
        }


2022-09-20 17:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.