java Array 크기순으로 값 정렬하기

조회수 4919회
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);

}

}

이코드를 실행해도 배열 안의 항목들이 작은것부터 큰순서로 정렬되어 출력되지 않는데

어느부분이 잘못된건가요?? ㅠㅠ

  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • 정렬 알고리듬은 여러가지가 있습니다.

    코드만 보고 판단이 쉽지는 않지만 버블정렬을 하려고 했던 것 같습니다.

    버블정렬은 각 요소들에 대해 비교반복을 해야 되므로 중첩 for 가 되어야 합니다.(퀵소트 같이 분할정복하는 알고리듬 외엔 기본적인 정렬알고리듬은 중첩for문이 됩니다.

    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; i++) {    // 리스트 길이만큼 반복
                for(int t = 0; t < list.length - 1; t++) { // 비교대상은 리스트보다 1개 적다.
                    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);    // 불필요한 코드
        }
    }
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)