Problems during bubble sorting implementation using Java.

Asked 2 years ago, Updated 2 years ago, 27 views

import java.util.Scanner;

public class BubbleSort {
    public static void main(String[] args) {
        int inputNumber = 0, temp = 0;
        int[] bubbleArray = new int[5];

        Scanner scanner = new Scanner(System.in);

        System.out.println("============================");
        for(int i = 0; i < bubbleArray.length; i++) {
            System.out.print("Input Number : ");
            inputNumber = scanner.nextInt();
            bubbleArray[i] = inputNumber;
        }

        for(int i = 0; i < bubbleArray.length; i++) {
            for(int j = 1; j < bubbleArray.length - 1; j++) {
                if(bubbleArray[i] > bubbleArray[j]) {
                    temp = bubbleArray[i];
                    bubbleArray[i] = bubbleArray[j];
                    bubbleArray[j] = temp;
                } } else {
                    break;
                }
            }
        }

        System.out.println("Complete Bubble Sorting Result :" + bubbleArray);
        System.out.println("============================");
        scanner.close();
        System.exit(0);
    }
}

We are writing a code that performs bubble sorting by simply inputting 5 numbers randomly. If you sort and print out the values entered in inputNumber, you will see a strange number like below. What's the problem?

java

2022-09-22 15:31

1 Answers

You can think of an array as a set of values. If you output an array directly, as you asked, the address value of the array is printed.

Certain values in an array are accessed through an index. Below are some examples.

int[] bubbleArray = {1, 2, 3, 4, 5};

System.out.println(bubbleArray); // Address value output
System.out.println(bubbleArray[0]); // 1

for (int index = 0; index < bubbleArray.length; index++) {
    System.out.println(bubbleArray[index]);
} 

for (int index : bubbleArray) {
    System.out.println(index);
}

System.out.println(Arrays.toString(bubbleArray));


2022-09-22 15:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.