import java.util.Scanner;
public class Main {
public static int sort(int[] arr) {
int count = 0;
// 비교 범위에 대한 루프
for (int i = arr.length - 1; i > 0; i--) {
boolean flag = false; // 정렬의 기능향상
// 실제 비교
for (int j = 0; j < i; j++) { // 왼쪽이 더 크면 자리 바꿈
// swap
if(arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
flag = true; //
count++;
}
}
if(!flag) break; // swap이 한번도 일어나지 않음음
} return count;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] a = new int[N];
for (int i = 0; i < N; i++) {
a[i] = sc.nextInt();
}
System.out.println(sort(a));
}
}
// 시간 초과가 떠서 아래에 버퍼드 리더로도 해봤는데 또 시간초과.. 버블소트로는 시간초과가 나오는 문제였음.. 도전중
===================================================
package datastructure.chap06.bubble;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class 버블_소트_1517 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int[] a = new int[N];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
a[i] = Integer.parseInt(st.nextToken());
}
int count = 0;
// 비교 범위에 대한 루프
for (int i = a.length - 1; i > 0; i--) {
// 실제 비교
for (int j = 0; j < i; j++) { // 왼쪽이 더 크면 자리 바꿈
// swap
if(a[j] > a[j + 1]) {
count++;
}
}
}
System.out.println(count);
}
}
'코딩테스트(연습)' 카테고리의 다른 글
22.06.14_프로그래머스_H-index_42747 (0) | 2022.06.14 |
---|---|
22.06.14_K_번째수_프로그래머스_42748 (0) | 2022.06.14 |
22.06.13_백준_오큰수_17298 (버퍼드리더활용) (0) | 2022.06.13 |
22.06.13(백준_ATM_11399) (0) | 2022.06.13 |
22.06.13(백준_소트인사이드_1427번) (0) | 2022.06.13 |