728x90
반응형
선택 정렬 정리내용
[백준]
23889번: 알고리즘 수업 - 선택 정렬5
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main{
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static BufferedWriter bf = new BufferedWriter(new OutputStreamWriter(System.out));
public static String selection_sort( int[] A, int[] B ) {
int maxIndex=0;
// 처음부터 똑같은 배열일 경우
if(Arrays.equals(A, B)) {
return "1";
}
// 선택 정렬
for (int i=A.length-1; i>0; i--) {
maxIndex = i;
for(int j=0; j<=i; j++) {
if(A[maxIndex] < A[j]) {
maxIndex = j;
}
}
// 자리 바꿈(큰 수가 뒤로)
if(i != maxIndex) {
int AValue = A[i];
A[i] = A[maxIndex];
A[maxIndex] = AValue;
// 자리가 바뀐 배열A와 배열 B가 같을 경우
if(Arrays.equals(A, B)) {
return "1";
}
}
}
// 배열A와 배열B가 같지 않을 경우
return "0";
}
public static void main(String[] args) {
try {
int n = Integer.parseInt(br.readLine()); // 배열 개수 입력
StringTokenizer stA = new StringTokenizer(br.readLine()); // 배열A 입력
StringTokenizer stB = new StringTokenizer(br.readLine()); // 배열B 입력
// 배열A, B 선언
int[] A = new int[n];
int[] B = new int[n];
for(int i=0; i < n; i++) {
// 배열 원소 넣기
A[i] = Integer.parseInt(stA.nextToken());
B[i] = Integer.parseInt(stB.nextToken());
}
bf.write( selection_sort(A, B) );
bf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
백준 23881번과 유사한 코드이나 교환 횟수 변수를 삭제하고 두 개의 배열을 입력받고 조건을 추가해 줌.
2022.03.11 - [코딩 테스트] - [자료구조와 알고리즘: JAVA 백준] 코딩테스트 연습 - 선택 정렬1
# JAVA에서 배열 비교
: Arrays.equals(배열1, 배열2)
※ 제출 시 틀린 이유
: 처음에 똑같은 배열이 입력 되었을 때의 조건을 만들어 주지 않음.
반응형
728x90
'코딩 테스트' 카테고리의 다른 글
[자료구조와 알고리즘: JAVA 백준] 코딩테스트 연습 - 에디터 (0) | 2022.03.12 |
---|---|
[자료구조와 알고리즘: JAVA 백준] 코딩테스트 연습 - 선택 정렬1 (0) | 2022.03.11 |
[자료구조와 알고리즘: JAVA 프로그래머스] 코딩테스트 연습 - 입국심사 (0) | 2022.02.25 |