자바 선택정렬(Selection Sort)
2020. 5. 9. 15:06ㆍ자료구조와 알고리즘
기준이 되는 수를 정하고 그 수와 나머지를 비교하여 가장 낮은 수를 제일 앞으로 보내는 정렬입니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SelectionSort { | |
public static void main(String[] args) { | |
// [1] 입력 | |
int[] data = { 7, 3, 5, 1, 9 }; | |
// [2] 처리 | |
// Arrays.sort(data); //이미 만들어진 API를 이용하면 쉽게 정렬할수있음. | |
// Selection Sort | |
int temp = 0; // 데이터 Swap용 임시 변수 | |
for (int i = 0; i < data.length - 1; i++) { | |
for (int j = i + 1; j < data.length; j++) { | |
if (data[i] > data[j]) { | |
// 오름차순으로 큰 수를 뒤로 보내는 조건: data[i] > data[j] | |
// 내림차순으로 큰 수를 앞으로 보내는 조건: data[i] < data[j] | |
// 데이터 값 Swap | |
temp = data[i]; | |
data[i] = data[j]; | |
data[j] = temp; | |
} | |
} | |
// ShowArray(data); // 현재 i번째 데이터 출력 | |
} | |
// [3] 출력 | |
System.out.println("====== 정렬 결과 ======"); | |
for (int i = 0; i < data.length; i++) { | |
System.out.print(data[i] + " "); // 1, 3, 5, 7, 9 출력되도록 | |
} | |
} | |
} |
코드프레소 DevOps Roasting Course 2기 진행중입니다.
'자료구조와 알고리즘' 카테고리의 다른 글
백준 2439번 별 찍기2 (0) | 2020.05.15 |
---|---|
백준 2438번 별 찍기 (0) | 2020.05.06 |
백준 11021번 A+B (0) | 2020.04.30 |
백준 2742번 기찍 N (0) | 2020.04.30 |
백준 2741번 N 찍기 (0) | 2020.04.28 |