Search code examples
javaarrayssortingbubble-sort

Method doesn't take proper array


My code will properly sort the numbers, but when it outputs the arrays, its the sorted one repeated twice. I want it to output the original array, and then the sorted array. It has to be split up into different methods this way. Here is my current code:

import javax.swing.*;
import java.io.*;
import java.util.*;

public class Gates_sortingBubble{

public static void main(String[] args)throws IOException{

  JOptionPane.showMessageDialog (null, "Please enter five numbers.", "Sorting Arrays", JOptionPane.INFORMATION_MESSAGE);

  String number1s;
  number1s = JOptionPane.showInputDialog("Number 1: ");
  int number1 = Integer.parseInt(number1s);

  String number2s;
  number2s = JOptionPane.showInputDialog("Number 2: ");
  int number2 = Integer.parseInt(number2s);

  String number3s;
  number3s = JOptionPane.showInputDialog("Number 3: ");
  int number3 = Integer.parseInt(number3s);

  String number4s;
  number4s = JOptionPane.showInputDialog("Number 4: ");
  int number4 = Integer.parseInt(number4s);

  String number5s;
  number5s = JOptionPane.showInputDialog("Number 5: ");
  int number5 = Integer.parseInt(number5s);

  int[] numbers = {number1, number2, number3, number4, number5};

  sort(numbers);

}

public static void sort(int[] tosort){

  int[] original = tosort;

  int j;
  boolean flag = true;     //set flag to true to begin first pass
  int temp;       //to hold the variable

  while(flag){       
     flag= false;  
     for( j=0;  j < tosort.length -1;  j++ ){
        if ( tosort[ j ] < tosort[j+1] ){  
           temp = tosort[ j ];              
           tosort[ j ] = tosort[ j+1 ];
           tosort[ j+1 ] = temp;
           flag = true;  
        }
     }
  } 

Is this how you send two variables into the method? Or is this where the mistake is?

  print(tosort, original);
}   


public static void print(int[] sorted, int[] unsorted){

  JOptionPane.showMessageDialog (null, "Your original five numbers are: " + Arrays.toString(unsorted) + ". \nYour new five numbers are: " + Arrays.toString(sorted) + ".", "Sorted Arrays", JOptionPane.INFORMATION_MESSAGE);

   //Arrays.toString(sorted)

} 
}

Solution

  • You could use:

    int[] original  = tosort.clone();
    

    This will copy all the elements to the orginal array.