-3

I am trying to sort an array in descending order. The size of the array comes from user input, and then the contents of the array come from user input. Then the array is passed to a function that sorts it. The issue is that, instead of printing a sorted array, it prints [I@5caf905d. Through print statements, I have pinpointed the problem to the scanner picking up [I@5caf905d as the final value from user input, coming right after all the correct inputs. I don't know where this value came from, and I also don't understand why it is printed by the function as if it were the entire array. All help is appreciated!

Here is my code. Input is: 5 10 4 39 12 2.


import java.util.Scanner;

public class LabProgram 
{
   public static void sortArray (int [] myArr, int arrSize)
   {
      int temp;
      int i;
      
      for (i = 0; i < arrSize - 1; i++)
      {
         if (myArr[i] < myArr[i + 1])
         {
            temp = myArr[i];
            myArr[i] = myArr[i + 1];
            myArr[i + 1] = temp;
         }          
      }
      System.out.println(myArr);
   }

   public static void main(String[] args) 
   {
      Scanner scnr = new Scanner (System.in);
      int [] myArr;
      int arrSize;
      int i; 
      
      
      arrSize = scnr.nextInt();
      myArr = new int[arrSize];
      for (i = 0; i < arrSize; i++)
         myArr[i] = scnr.nextInt();
         
      sortArray (myArr, arrSize);  
   }
}

1 Answers1

0

You should use one of the simpliest sorting algorithm e.g. Selection Sort:

public static void selectionSortDesc(int[] arr) {
    for(int i = 0; i < arr.length; i++) {
        // k index with max value
        int k = i;
        
        // find k with max value
        for(int j = i; j < arr.length; j++) {
            if(arr[k] < arr[j])
                k = j;
        }
        
        // swap current element with the max value
        swap(arr, i, k);
    }
}

private static void swap(int[] arr, int i, int j) {
    int tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = arr[i];
}

By the way, you should not mix sorting and printing the array. It's better to split these parts.

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35