- ์๊ฐ๋ณต์ก๋ : O(n2)
ใด ํ๋๋ swap๊ฐ ์ผ์ด๋์ง ์์ ๊ฒฝ์ฐ์ ํด์ ์ข ๋ฃํ๋ ๋ณ์๋ฅผ ๋์ด ์ฑ๋ฅ์ ๊ฐ์ ํ ์ ์์.
for (int i = 1; i < a.size(); i ++) {
boolean swapped = false;
for (int j = 0; j < (a.size() - i); j++) {
if (a.get(j) > a.get(j + 1)) {
int temp = a.get(j + 1);
a.set(j + 1, a.get(j));
a.set(j, temp);
swapped = true;
}
}
// ํด ์ข
๋ฃ
if(swapped == false) {
break;
}
}
๋ด ์์ค์ฝ๋
๋๋ณด๊ธฐ
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'countSwaps' function below.
*
* The function accepts INTEGER_ARRAY a as parameter.
*/
public static void countSwaps(List<Integer> a) {
// Write your code here
int swaps = 0;
for (int i = 1; i < a.size(); i ++) {
// debug
// System.out.println(i + " : " + a.get(i));
for (int j = 0; j < (a.size() - i); j++) {
// debug
// System.out.println(i + " : " + a.get(j) + " > " + a.get(j + 1) );
if (a.get(j) > a.get(j + 1)) {
int temp = a.get(j + 1);
a.set(j + 1, a.get(j));
a.set(j, temp);
swaps++;
}
}
// debug
// System.out.println(i + " : " + a.get(i));
// System.out.println(a);
}
System.out.println(String.format("Array is sorted in %s swaps.", swaps));
System.out.println(String.format("First Element: %s ", a.get(0)));
System.out.println(String.format("Last Element: %s ", a.get(a.size() - 1)));
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> a = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(toList());
Result.countSwaps(a);
bufferedReader.close();
}
}
๋ฐ์ํ
'๐ค ์๊ณ ๋ฆฌ์ฆ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
baekjoon. ๋ฌธ์์ด ํญ๋ฐ (0) | 2022.08.29 |
---|---|
programmers. ๋ค๋จ๊ณ ์นซ์ ํ๋งค (0) | 2022.06.29 |
์๊ณ ๋ฆฌ์ฆ ๊ฟํ. ์๋ฐ (0) | 2022.06.27 |
programmers. ํ๋ ฌ ํ ๋๋ฆฌ ํ์ ํ๊ธฐ (0) | 2022.06.26 |
programmers. ๋ก๋์ ์ต๊ณ ์์์ ์ต์ ์์ (0) | 2022.06.23 |