0

I want to bubble sort an array that could be any number with values from the user. But the first method is not working. I really want to use JOptionPanes, but I don't even know if that is the problem. It compiles correctly, but doesn't run properly. This 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{

  String amountS;
  amountS = JOptionPane.showInputDialog(null, "How many numbers would you like to sort?", 
        "Sorting Arrays", JOptionPane.INFORMATION_MESSAGE);
  int amount = Integer.parseInt(amountS);

  JOptionPane.showMessageDialog (null, "Please enter " + amount + " numbers you wish to sort.", 
        "Sorting Arrays", JOptionPane.INFORMATION_MESSAGE);

  int[] numbers = new int [amount];

  for(int i = 1; i <= amount; i++){
     String tempS = JOptionPane.showInputDialog("Number " + i + ": ");
     int temp = Integer.parseInt(tempS);
     numbers[i] = temp; 
  }

  sort(numbers);

}

public static void sort(int[] tosort){

  int[] original  = tosort.clone();

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

  while(flag){       
     flag= false;   //set flag to false awaiting a possible swap
     for( j=0;  j < tosort.length -1;  j++ ){
        if ( tosort[ j ] < tosort[j+1] ){  
           temp = tosort[ j ];     //swap the array elements
           tosort[ j ] = tosort[ j+1 ];
           tosort[ j+1 ] = temp;
           flag = true;       //shows a swap occurred 
        }
     }
  } 

  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);
}


}
  • What I don't understand is the boolean variable `flag` and it's purpose in the code, anyway see this [Bubble Sort](http://www.roseindia.net/java/beginners/arrayexamples/bubbleSort.shtml).One last thing :I don't believe you have anything in your code that throws IOException –  Dec 08 '13 at 23:45
  • 1
    @OssamaNasser That's the `swapped` check from the algorithm. It's an improvement over the naive implementation which you linked, since it stops when it notices that the array is already (or became) sorted. Either way, I don't see why the OP would want to use bubble sort, let alone implement it. – Mattias Buelens Dec 08 '13 at 23:50

1 Answers1

0

Your for loop in the main method goes from 1 to amount, but the array indexes of the numbers array range from 0 to amount-1. So in that loop, change:

numbers[i] = temp;

To:

numbers[i - 1] = temp;

And it will work.

Boann
  • 48,794
  • 16
  • 117
  • 146