To sort values by java Array size

Asked 2 years ago, Updated 2 years ago, 51 views

package practice_3;
import javax.swing.JOptionPane;

public class ArrayExcercise1 {
public static void main(String[]args) {
        int[] list = new int[10];
    String print = "";
    for (int i = 0; i<list.length; i++) {
        list[i] = (int)(Math.random()*10);
    }//end of for i
    for (int i =0; i<list.length-1-i;i++) {
        if (list[i]<list[i+1]) {
            int temp=list [i];
            list[i] = list[i+1];
            list[i+1]=temp;
        }//end of if
    }//end of for i
    for(int i = 0; i<list.length;i++) {
         String st =  Integer.toString(list[i]);
         print+= st;
    }
    JOptionPane.showMessageDialog(null,print);
    System.exit(0);

}

}

Even if this code is executed, the items in the array are sorted in order from small to large and are not printed.

Which part is wrong? ㅠ<

java array bubble-sort

2022-09-21 15:38

1 Answers

There are several sorting algorithms.

It's not easy to judge just by looking at the code, but I think I tried to arrange bubbles.

Bubble sorting must be superimposed for each element because it must be compared and repeated for each element (except for algorithms that segment and conquer, such as QuickSort, the basic sorting algorithm becomes superimposed for statements.

package practice_3;
import javax.swing.JOptionPane;

public class ArrayExcercise1 {
    public static void main(String[]args) {
        int[] list = new int[10];
        String print = "";
        for (int i = 0; i < list.length; i++) {
            list[i] = (int)(Math.random()*10);
        }//end of for i

        for (inti = 0; i < list.length; i++) { // Repeat by list length
            For(int = 0; t < list.length - 1; t++) { // 1 less comparison target than list.
                if (list[t] > list[t + 1]) {
                    int temp = list[t];
                    list[t] = list[t+1];
                    list[t + 1] = temp;
                }//end of if
            }

        }//end of for i

        for(int i = 0; i<list.length;i++) {
             String st =  Integer.toString(list[i]);
             print+= st;
        }
        JOptionPane.showMessageDialog(null,print);
        //System.exit(0); // Unnecessary code
    }
}


2022-09-21 15:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.