Mathlife
Mathlife의 학습 노트
Mathlife
전체 방문자
오늘
어제
  • 분류 전체보기
    • CS
      • 알고리즘
      • 자료구조
      • 운영체제
      • 네트워크
      • 데이터베이스
    • 프로그래밍 언어
      • Java
      • JavaScript
      • C·C++
      • Python
    • Backend
      • Spring
    • Frontend
      • HTML
      • CSS
    • Math
      • Linear Algebra
      • Calculus
    • AI
      • ML
      • DL
      • RL
    • Git

블로그 메뉴

  • 홈
  • 관리
  • 글쓰기
  • 태그
  • 방명록

공지사항

인기 글

태그

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Mathlife

Mathlife의 학습 노트

CS/알고리즘

Merge Sort & Quick Sort (JAVA)

2022. 4. 20. 01:45

Merge Sort

- best : $\ O(n \log{n})$

- avg : $\ O(n \log{n})$

- worst : $\ O(n \log{n})$

- out-of-place

- stable

public static void mergeSort(int[] arr, int low, int high) {
    if (high-low < 1)
        return;

    int mid = (low+high)/2;
    mergeSort(arr, low, mid);
    mergeSort(arr, mid+1, high);

    int[] tmp = new int[high-low+1];
    int i = low, j = mid+1, idx = 0;
    while (i <= mid && j <= high) {
        if (arr[i] <= arr[j])
            tmp[idx++] = arr[i++];
        else
            tmp[idx++] = arr[j++];
    }
    while (i <= mid)
        tmp[idx++] = arr[i++];
    while (j <= high)
        tmp[idx++] = arr[j++];

    for (int k = 0; k < tmp.length; k++)
        arr[low + k] = tmp[k];
}

 

Quick Sort

- best : $\ O(n \log{n})$

- avg : $\ O(n \log{n})$

- worst : $O(n^2)$

- in-place 

- unstable

public static void swap(int[] arr, int from, int to) {
    int tmp = arr[from];
    arr[from] = arr[to];
    arr[to] = tmp;
}

public static void quickSort(int[] arr, int low, int high) {
    if (high-low < 1)
        return;

    int pivot = high;
    int i = low; // the first index s.t. arr[idx] > arr[pivot]

    for (int j = low; j < high; j++) {
        if (arr[j] <= arr[pivot])
            swap(arr, i++, j);
    }

    swap(arr, i, pivot);
    quickSort(arr, low, i-1);
    quickSort(arr, i+1, high);
}

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

BBST / union-find  (0) 2022.05.06
DFS/BFS  (0) 2022.05.06
LCS  (0) 2022.04.05
그래프 사이클 관련 문제  (0) 2022.03.28
에라토스테네스의 체  (0) 2022.03.28
    'CS/알고리즘' 카테고리의 다른 글
    • BBST / union-find
    • DFS/BFS
    • LCS
    • 그래프 사이클 관련 문제
    Mathlife
    Mathlife

    티스토리툴바