티스토리 뷰

[주제]

- 정렬 방식 중 버블정렬 구현



[중요]

- 'temp' 변수를 사용하여 두 개의 변수 값을 서로 교환하기



[소스 코딩]

package sortingClass;
 
import java.util.Scanner;
 
class sortingClass {
    public static void main(String[] args) {
/*
    sorting(정렬)
    버블 정렬 구현
*/
    Scanner scan = new Scanner(System.in);
    
    int num[];
    int count, updown, temp;
    count = updown = temp = 0;
 
//  정렬할 개수를 입력
    System.out.print("정렬할 개수 입력: ");
    count = scan.nextInt();
 
//  입력된 개수만큼 동적할당
    num = new int[count];
 
//  정렬할 숫자를 입력
    for(int i=0; i < num.length; i++) {
        System.out.print((i + 1+ "번째 수 입력: ");
        num[i] = scan.nextInt();
    }
 
//  올림차순 or 내림차순 설정
    System.out.print("올림차순(1)/내림차순(2) = ");
    updown = scan.nextInt();
 
//  정렬 시작
    for(int i=0; i < count - 1; i++) {
        for(int j=i+1; j < count; j++) {
            if(updown == 1) {
                if(num[i] > num[j])    {
                temp = num[i];
                num[i] = num[j];
                num[j] = temp;
                }
            }
            else {
                if(num[i] < num[j])    {
                temp = num[i];
                num[i] = num[j];
                num[j] = temp;
                }
            }
        }
    }
 
//  출력
    for(int i=0; i < num.length; i++) {
        System.out.println((i + 1+ "번째 수 = " + num[i]);
    }
    scan.close();
    }
}
cs



■ 실행결과


'프로그래밍 언어 > Java(연습)' 카테고리의 다른 글

method(함수, 메소드)  (0) 2016.04.27
야구 게임  (0) 2016.04.27
로또 번호 추첨 프로그램  (0) 2016.04.26
cast(형변환)  (0) 2016.04.26
string2(진수 변환)  (0) 2016.04.25
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함