선택정렬 알고리즘

·2023년 5월 5일

자바 알고리즘

목록 보기
2/2
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Select_Algorithm {
	public static void main(String[] args) {
		//선택 정렬 알고리즘 문제
		//입력 : 정렬할 수 N이 주어진다. N은 1,000,000,000보다 작거나 같은 자연수.
		//출력 : 자릿수를 내림차순 정렬한 수를 출력한다. ex) 2143 -> 4321
		Scanner sc = new Scanner(System.in);
		
		List<Integer> num = new ArrayList<>();
		//입력
		int N = Integer.parseInt(sc.nextLine());
		//1의 자리부터 거꾸로 저장
		while(N>0) {
			num.add(N % 10);
			N /= 10;
		}

		int startIndex = 0;
		while(startIndex<num.size()-1) {
			int maxIndex = startIndex;
			int temp = 0;
			//max 값 선택
			for(int i=startIndex; i<num.size(); i++) {
				if(num.get(i) > num.get(maxIndex)) {
					maxIndex = i;
				}
			}
			//swap
			temp = num.get(startIndex);
			num.set(startIndex,num.get(maxIndex));
			num.set(maxIndex, temp);
			startIndex++;
		}
		
		//출력
		for(int value : num) {
			System.out.print(value);
		}
		System.out.println();
	}

}
profile
이것저것 공부하기

0개의 댓글