본문 바로가기

알고리즘

배열 내림차순 정렬

728x90

문제:

배열을 오름차순으로 정렬하려면

 

import java.util.Arrays;

Arrays.sort(배열);

 

내림차순으로 정렬하려면

Arrays.sort(배열, Collections.reverseOrder());

로 알고 있었는데 오류가 났다.

 

/Solution.java:7: error: no suitable method found for sort(int[],Comparator<Object>)
Arrays.sort(people, Collections.reverseOrder());
^
method Arrays.<T#1>sort(T#1[],Comparator<? super T#1>) is not applicable
(inference variable T#1 has incompatible bounds
equality constraints: int
lower bounds: Object)
method Arrays.<T#2>sort(T#2[],int,int,Comparator<? super T#2>) is not applicable
(cannot infer type-variable(s) T#2
(actual and formal argument lists differ in length))
where T#1,T#2 are type-variables:
T#1 extends Object declared in method <T#1>sort(T#1[],Comparator<? super T#1>)
T#2 extends Object declared in method <T#2>sort(T#2[],int,int,Comparator<? super T#2>)
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

 

해결 방법:

int형 배열을 그대로 정렬하면 안되고 Integer형으로 바꿔줘야 한다.

import java.util.Arrays;
import java.util.Collections;
//import java.util.Comparator;

public class Main {
    public static void main (String[] agrs) {

      // 정렬할 배열
      int[] arr = {8, 3, 5, 1, 7, 0};

      // Integer배열 생성
      Integer[] arr2 = Arrays.stream(arr).boxed().toArray(Integer[] :: new);
      // 내림차순 정렬
      Arrays.sort(arr2, Collections.reverseOrder());
      // Arrays.sort(arr2, Comparator.reverseOrder()); 같은 결과

      System.out.println(Arrays.toString(arr2));

      // int배열 생성
      int[] desc = Arrays.stream(arr2).mapToInt(i -> i).toArray();
      System.out.println(Arrays.toString(desc));		

    }		
}

'알고리즘' 카테고리의 다른 글

프로그래머스42885 - 이중 for문 성능 올리기  (0) 2021.02.24
백준 11399 String[] -> Int[]  (0) 2021.02.18
백준 16435 BufferedReader와 Scanner  (0) 2021.02.17
탐욕(그리디) 알고리즘  (0) 2021.02.16
1로 만들기  (0) 2021.02.06