본문 바로가기

old/Programming

병합정렬 Merge Sort

반응형

정의

오름차순으로 정렬하는 기초적인 알고리즘 중 하나

기법

분할 정복 Divide and Conquer

알고리즘 순서

  1. 재귀적으로 반씩 나누어서 모든 요소가 1이 될 때까지 나눔
  2. 요소가 1이므로, 이는 정렬된 배열임.
  3. 이 배열을 차근차근 합침

자바 코드


   public static void mergeSort(int[] input) {
        mergeSortRecurr(input, 0, input.length - 1);
    }

    public static void mergeSortRecurr(int[] input, int left, int right) {
        if (left < right) {
            int midPos = left + (right - left) / 2;

            mergeSortRecurr(input, left, midPos);
            mergeSortRecurr(input, midPos + 1, right);
            merge(input, left, right, midPos);
        }
    }

    public static void merge(int[] input, int left, int right, int midPos) {
        //mid pos does not check unlike the left and right
        int temp1 = midPos - left + 1;
        int temp2 = right - midPos;

        //temp array and copy
        int[] L = new int[temp1];
        int[] R = new int[temp2];
        for (int i = 0; i < temp1; ++i)
            L[i] = input[left + i];
        for (int j = 0; j < temp2; ++j)
            R[j] = input[midPos + 1 + j];


        int i = 0;
        int j = 0;
        int k = left;

        while (i < temp1 && j < temp2) {
            if (L[i] <= R[j]) {
                input[k] = L[i];
                ++i;
            } else {
                input[k] = R[j];
                ++j;
            }
            ++k;
        }

        while (i < temp1) {
            input[k] = L[i];
            ++i;
            ++k;
        }

        while (j < temp2) {
            input[k] = R[j];
            ++j;
            ++k;
        }
    }

평균 시간 복잡도 Avg. time complexity

$O(n, log, n)$

최악 시간 복잡도 Worst time complexity

$O(n, log, n)$

공간 복잡도 space complexity

$O(n)$

안정성 stability

yes

계산법

순회 횟수

  • 좌우가 균등하게 나뉘면 : $O(log, n)$
  • 하나씩 다시 병합되는 루프: $O(n)$

$O(n) \cdot O(log, n)=O(n, log, n)$

반응형