본문 바로가기

자바 Do,It 알고리즘(끝)

[자바 Do It! 알고리즘]Chapter06 정렬 (병합 정렬-Arrays.sort로 퀵 정렬과 병합정렬하기)

[Arrays.sort로 퀵 정렬과 병합 정렬하기]

1. 이진 검색에 사용했던 binarySearch 메서드는 java.util.Araays 클래스의 클래스 메서드로 제공합니다. 이 클래스는 배열을 정렬하는 클래스 메서드 sort도 제공합니다.

1 static void sort(byte[] a)
2 static void sort(byte[] a, int fromIndex, int tolndex)
3 static void sort(char[] a)
4 static void sort(char[] a, int fromIndex, int tolndex)
5 static void sort(double[] a)
6 static void sort(double[] a, int fromIndex, int tolndex)
7 static void sort(float[] a)
8 static void sort(float[] a, int fromIndex, int tolndex)
9 static void sort(int[] a)()
10 static void sort(int[] a, int fromIndex, int tolndex)
11 static void sort(long[] a)
12 static void sort(long[] a, int fromIndex, int tolndex)
13 static void sort(short[] a)
14 static void sort(short[] a, int fromIndex, int tolndex)
15 static void sort(Object[] a)
16 static void sort(Object[] a, int fromIndex, int tolndex)
17 static void sort(T[] a, Comparator<? super T> c)
18 static void sort(T[] a, int fromIndex, int tolndex, Comparator<? super T> c)

위 표에 정리한 메서드는 모두 배열 a를 기준으로 오름차순으로 정렬합니다.

홀수번호의 sort는 배열 a의 모든 요소를 정렬합니다.

짝수번호의 sort는 a[fromIndex] ~ a[toIndex]가 정렬 대상입니다.

[기본 자료형 배열의 정렬(퀵 정렬)]

1. sort 메서드가 사용하는 알고리즘은 퀵 정렬 알고리즘을 개선한 것으로 안정적이지 않습니다. 즉 배열에 같은 값이 존재하는 경우 같은 값 사이의 순서가 뒤바뀔 수 있습니다.

기본자료형의 배열(퀵정렬)

[클래스 객체 배열의 정렬(병합 정렬)]

1. 클래스 객체 배열을 정렬하는 메서드는 15~18번의 메서드이며 크게 두 종료루 나뉩니다.

2. 자연 정렬이 필요한 배열

1) 요소의 대소 관계를 비교하여 정렬합니다.

static void sort(Object[] a)

static void sort(Object[] a, int fromIndex, int tolndex)

메서드로 GregorianCalendar 형의 배열을 정렬하는 프로그램입니다.

3. 자연 정렬이 필요하지 않은 배열

1) 요소의 대소 관계를 비교할 때 comparator c를 사용하여 정렬합니다.

static void sort(T[] a, Comparator<? super T> c)

static void sort(T[] a, int fromIndex, int tolndex, Comparator<? super T> c)

메서드로 정렬하는 프로그램입니다.