1

I have a program here that calculated the median of a certain amount of elements entered by a user; however I want to display the sorted list at the end of the program. You can see that I have sorted the elements but I can't think of any ways to display the sorted array at the end. Thanks in advance.

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in);

    System.out.println("How many numbers do you want a median of?");
    int num = sc.nextInt();

    System.out.println("Enter the numbers: ");
    int [] array = new int [num];

    for (int i = 0 ; i < array.length; i++ ) {
      array[i] = sc.nextInt();
    }

    int median = median(array);
    System.out.println(median+" is a median of entered numbers.");
}


public static int median (int [] array) {

  int n = array.length;
  int temp;   
  for (int i=0; i < n-1; i++) {
    for(int j=1; j < n-i; j++) {
      if (array [j-1] > array [j]) {
        temp = array [j-1];
        array [j-1] = array [j];
        array  [j] = temp;
      }
    }
  }
  int median;
  if (n % 2 == 0) {
    median = (array [n/2-1]);
  }
  else {
    median = array [(n/2)];
  }
  return median;
  }
}
user1803551
  • 12,965
  • 5
  • 47
  • 74
Rawrqqplz
  • 21
  • 3
  • You know how to print individual numbers, and you know how to access all the elements of an array, so you know how to print the values in an array. – Scott Hunter Oct 21 '14 at 19:22
  • @Andreas: I suspect this isn't so much about printing the array, but about thinking (incorrectly) that the sorted array is not available in `main`. Then again, I could be wrong. – Eric J. Oct 21 '14 at 19:25
  • @EricJ. Yes, you are probably right - not completely sure either, but you might want to refer to `java.util.Arrays` in your answer as an alternative to a manual loop ;) – Andreas Fester Oct 21 '14 at 19:26
  • @EricJ. OPs comment to the answer from Fernando suggests that you are right ... – Andreas Fester Oct 21 '14 at 19:29

2 Answers2

2

In the function

public static int median (int [] array) 

you pass array by reference. That means that the result of your sorting will be visible in main. You are sorting the array in place.

At the end of main, simply setup a loop that prints each element of the array.

Eric J.
  • 147,927
  • 63
  • 340
  • 553
2

If I understood correctly, you need just to print an array? After your int median(int []) method is called, the array is already sorted. You just print it like:

for(int i = 0; i < array.length; i++)
    System.out.println(array[i]);

The array var is an Object (all arrays are objects in Java), so you send through the method call just the pointer to the object, not a copy of the object.

Hope that helps.

Fernando Aires
  • 532
  • 2
  • 7
  • 1
    yes thank you so much I didn't realize that once I called the method the sorted list had already been stored in the main method. – Rawrqqplz Oct 21 '14 at 19:28