Contents:
1. Program Description 2. Code
3. Output Screenshots
Program Description:
This program is a Java GUI solution using the Swing package to sort the input integers/fractions into the text field.
To sort the values
-> i. Enter the integers/fractions into the text field, with each value separated by a space.
-> ii. Choose the kind of value entered and the sorted order required -> iii. Click perform sort
Code Files:
BST.java // BST
// Nodes added in a specific order of the keys // No two key values are the same
public class BST <KeyType extends Comparable<KeyType>, ValueType> { private BSTNode root;
private int size;
private class BSTNode {
KeyType key; // sorted by key ValueType value; // value for the key
BSTNode left, right; // left and right subtrees
public BSTNode(KeyType key, ValueType value) { this.key = key;
this.value = value;
left = null;
right = null;
} }
// Constructor to initialize roots public BST() {
root = null;
size = 0;
}
// To check if the BST is empty. This is when root node is null
public boolean isEmpty() { return root == null;
}
// Make the BST empty. Set root to null.
public void makeEmpty() { root = null;
size = 0;
}
// adds key-value pair to the root.
public void add( KeyType key, ValueType value ) throws IllegalArgumentException{
// if key is null if ( key == null ) {
throw new IllegalArgumentException();
}
// if root is null, we assign root node the key and value if ( root == null ) {
this.root = new BSTNode( key, value );
size++;
} else {
root = add( root, key, value );
size++;
} }
// adds key-value pair to the root if the root is not null
private BSTNode add(BSTNode node, KeyType key, ValueType value) { if( node == null ){
return new BSTNode(key, value);
}
int compare = key.compareTo( node.key );
if ( compare < 0 ) {
node.left = add( node.left, key, value );
} else {
node.right = add( node.right, key, value );
}
return node;
}
// to check if a key is present in the BST or not.
// corner cases handled as explained below
public String printTree(){
if( isEmpty( ) ) return "";
else
return printTree( root );
}
private String printTree(BSTNode node){
if( node == null ) return "";
String r = "";
if( node != null ){
r = r + printTree( node.left ) + " ";
r = r + node.key + " ";
r = r +printTree( node.right ) + " ";
}
return r;
}
} // end BinarySearchTree class
Fraction.java
public class Fraction implements Comparable<Fraction>
{
// to store the numerator private int numerator;
// to store the denominator private int denominator;
// the constructor
public Fraction(int numerator, int denominator) { this.numerator = numerator;
this.denominator = denominator;
}
// the constructor
public Fraction(String fraction) { // check for valid integers
int slashIndex = fraction.indexOf('/');
// check for valid integers
String num = fraction.substring(0, slashIndex);
String den = fraction.substring(slashIndex + 1);
numerator = Integer.parseInt(num);
denominator = Integer.parseInt(den);
}
// to get the value of this fraction public double getValue(){
// return the fraction value
return ((double)(numerator))/((double)(denominator));
}
// to check for valid fractions
public static boolean isValidFraction(String fraction){
// number of slashes must be one int numSlashes = 0;
// count the number of slashes for( int i=0; i<fraction.length(); i++){
if( fraction.charAt(i) == '/') numSlashes++;
}
// if more than one, return false if( numSlashes != 1 )
return false;
// check for valid integers
int slashIndex = fraction.indexOf('/');
// if this is 0, or last, return false
if( slashIndex == 0 || slashIndex == fraction.length() - 1) return false;
// check for valid integers
String num = fraction.substring(0, slashIndex);
String den = fraction.substring(slashIndex + 1);
// check validity
// try to convert the numerator to integer try{
// try to convert this string to integer Integer.parseInt( num );
}
// catch the exception
catch( NumberFormatException e ){
// return false return false;
}
// try to convert the denominator to integer try{
// try to convert this string to integer Integer.parseInt( den );
}
// catch the exception
catch( NumberFormatException e ){
// return false return false;
}
// if everything passes, return true return true;
}
@Override
public int compareTo(Fraction o) { //
if( getValue() > o.getValue() ) return 1;
else if( getValue() == o.getValue() ) return 0;
else
return -1;
}
// the to string
public String toString(){
return (numerator + "/" + denominator);
} }
Sorting.java
public class Sorting<T extends Comparable<T>>{
// thE orders
public static final int ASCENDING_ORDER = 1;
public static final int DESCENDING_ORDER = 2;
// to sort a list
public void sort(T a[], int order){
// use bubble sort
for( int i=0; i<a.length; i++){
// the inner loop
for( int j=0; j<a.length - 1; j++){
// based on the order
if( order == ASCENDING_ORDER ){
// SWAP
if( a[j].compareTo( a[j+1]) > 0){
// the temp T temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
} }
else if( order == DESCENDING_ORDER ){
// SWAP
if( a[j].compareTo( a[j+1]) < 0){
// the temp T temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
} }
} }
} }
GUI.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class GUI extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
// the input text field
private JTextField inputTextField = new JTextField(60);
// the output text field
private JTextField outputTextField = new JTextField(60);
// the button to perform the sorting
private JButton buttonPerformSort = new JButton("Perform Sort");
// the radio buttons
// the buttons for the order of sorting
JRadioButton ascending = new JRadioButton("Ascending");
JRadioButton descending = new JRadioButton("Descneding");
ButtonGroup sortOrder = new ButtonGroup();
// the type of values to be sorted
JRadioButton integers = new JRadioButton("Integer");
JRadioButton fraction = new JRadioButton("Fraction");
ButtonGroup valuetype = new ButtonGroup();
// the constructor public GUI(){
// add all the items the the gui add(new JLabel("Original List : "));
// add the original add(inputTextField);
// add all the items the the gui add(new JLabel("Sorted List : " ));
// add the original add(outputTextField);
// add the button
add(buttonPerformSort);
// add listener
buttonPerformSort.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) { // if integers is selected and not valid input if( integers.isSelected() && !isValidIntegerInput(
inputTextField.getText())){
// show message
JOptionPane.showMessageDialog(null,
"Non-numeric input!");
// clear the text field inputTextField.setText("");
}
// else if fraction selected, and invalid input
else if( fraction.isSelected() &&!isValidFractionInput(
inputTextField.getText()) ){
// show message
JOptionPane.showMessageDialog(null,
"Non-numeric input!");
// clear the text field inputTextField.setText("");
} else{
// if integers selected if( integers.isSelected() ){
// sort
// get the values Integer[] ints=
getIntegerValues(inputTextField.getText());
// create BST
BST<Integer,Integer> bst = new BST<>();
for( int i=0; i<ints.length; i++)
bst.add( ints[i], ints[i]);
// sort
// if ascending
if( ascending.isSelected() ){
// sort
outputTextField.setText(bst.printTree());
} else{
// sort
String out = "";
String toks[] = bst.printTree().split("
");
for( int i=toks.length-1; i>=0; i--) out += ( toks[i] + " " );
// sort
outputTextField.setText(out);
}
// outputTextField.setText(output);
}
else {// if fractions selected // sort
// get the values Fraction[] fractions=
getFractionValues(inputTextField.getText());
// create BST
BST<Fraction,Fraction> bst = new BST<>();
for( int i=0; i<fractions.length; i++) bst.add( fractions[i], fractions[i]);
// if ascending
if( ascending.isSelected() ){
// sort
outputTextField.setText(bst.printTree());
} else{
String out = "";
String toks[] = bst.printTree().split("
");
for( int i=toks.length-1; i>=0; i--) out += ( toks[i] + " " );
// sort
outputTextField.setText(out);
} }
}
} });
// add labels for the buttons add(new JLabel("Sort Order : "));
// add the buttons to the group sortOrder.add(ascending);
sortOrder.add(descending);
// add buttons to the GUI add(ascending);
add(descending);
// add the buttons to the group valuetype.add(integers);
valuetype.add(fraction);
// add buttons to the GUI
// add labels for the buttons
add(new JLabel("Numeric Type : "));
add(integers);
add(fraction);
// set default selections ascending.setSelected(true);
descending.setSelected(false);
integers.setSelected(true);
fraction.setSelected(false);
}
// check for valid input
private boolean isValidIntegerInput(String input){
if( input == null || input == "") return false;
// get tokens
String numbers[] = input.split(" ");
// check for all values
for( int i=0; i<numbers.length; i++) {
// if cannot convert to a number , return false
try {
// try to convert this string to integer Integer.parseInt( numbers[i] );
}
// catch the exception
catch( NumberFormatException e ){
// return false return false;
} }
// return true for valid return true;
}
// check for valid input
private boolean isValidFractionInput(String input) {
if( input == null || input == "") return false;
// get tokens
String fractions[] = input.split(" ");
// check for all values
for( int i=0; i<fractions.length; i++){
// if cannot convert to a number , return false if( !Fraction.isValidFraction( fractions[i] )){
// return false return false;
} }
// return true for valid
return true;
}
// get the list of values
private Integer[] getIntegerValues(String input) { // get tokens
String numbers[] = input.split(" ");
// the array of integers
Integer[] ints = new Integer[ numbers.length ];
// check for all values
for( int i=0; i<numbers.length; i++){
// try to convert this string to integer ints[i] = Integer.parseInt( numbers[i] );
}
// return the array return ints;
}
// get the list of fraction values
private Fraction[] getFractionValues(String input) { // get tokens
String fractions[] = input.split(" ");
// the array of integers
Fraction[] fs = new Fraction[ fractions.length ];
// check for all values
for( int i=0; i<fractions.length; i++){
// try to convert this string to integer fs[i] = new Fraction(fractions[i]);
}
// return the array return fs;
} }
Main.java
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Main {
// the main method
public static void main(String args[]){
// call the method to run the simulation SwingUtilities.invokeLater(new Runnable(){
public void run(){
Main.createAndShowGUI();
} });
}
private static void createAndShowGUI() { // create the P3Main
GUI view = new GUI();
// create the frame
JFrame frame = new JFrame("Binary Search Tree Sort");
Container container = frame.getContentPane();
// add the panel to this frame container.add(view);
// set the frame size frame.setSize(900, 900);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
view.requestFocusInWindow();
} }
Output Screenshots 1:
Sorting Integers
Output Screenshots 2:
Sorting Fractions