How can to code sorting numbers (ascending/descending) via bubble sorting?

917 views Asked by At

I need help on using bubble sort and sorting it whether ascending or descending :(

          int[] number = {12, 5, 6, 14, 18};    

      int[] number = new int[5];
      String[] mark = new String[10];
      String evenOrOdd = "";
      String output = "";

      JTextArea textArea = new JTextArea(12,30);


      for(int i = 0; i < number.length; i++) {
        number[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter a number"));

        if (number[i] % 2 == 0) {
            evenOrOdd = "even";
        }
        else {
            evenOrOdd = "odd  ";
        }

        mark[i] = "";
        for(int j = 0; j < number[i]; j++) {
            mark[i] = mark[i] + "*"; 
        }

        output = output + number[i] + "\t"; 
        output = output + evenOrOdd + "\t";
        output = output + mark[i] + "\n";
      } 

      textArea.setText("numbers\ttype\tgraph\n" + output);
      JOptionPane.showMessageDialog(null, 
                        textArea,
                                   "OUTPUT",
                                   JOptionPane.INFORMATION_MESSAGE);    
      System.exit(0);   
    }
}

}

The code is missing the bubble sorting and I don't where to put it. Can someone please help me? It doesn't need the user to input anything,

1

There are 1 answers

0
Elliott Frisch On

The way you support ascending and descending is to pass a Comparator to your sort() method and use it to test the results of element comparisons like,

public static void bubbleSort(int[] numero, Comparator<Integer> comp) {
    int n = numero.length;
    int temp = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 1; j < (n - i); j++) {
            if (comp.compare(numero[j - 1], numero[j]) > 0) {
                temp = numero[j - 1];
                numero[j - 1] = numero[j];
                numero[j] = temp;
            }
        }
    }
}

Ascending is the default behavor for Comparable like Integer. So we can delegate to compareTo() like,

private static Comparator<Integer> ascending = new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o1.compareTo(o2);
    }
};

Then descending is the reverse of ascending, so delegate and reverse like

private static Comparator<Integer> descending = new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        return -ascending.compare(o1, o2);
    }
};

Then test it

public static void main(String arg[]) {
    int[] arr = { 10, 30, 20 };
    System.out.println(Arrays.toString(arr));
    bubbleSort(arr, ascending);
    System.out.println("Ascending: " + Arrays.toString(arr));
    bubbleSort(arr, descending);
    System.out.println("Descending: " + Arrays.toString(arr));
}

Output is

[10, 30, 20]
Ascending: [10, 20, 30]
Descending: [30, 20, 10]