algoalgo-world
algoalgo-world/sort/sleep-sort
sort/sleep-sort

슬립 정렬

최선
O(n * k)
평균
O(n * k)
최악
O(n * k)
공간
O(n)
안정성
안정
방식
분포 기반

k 는 값의 범위

언어를 고르면 코드가 열린다

def sleep_sort(a):
    if not a:
        return
    clock = [[] for _ in range(max(a) + 1)]
    for value in a:
        clock[value].append(value)
    i = 0
    for tick in range(len(clock)):
        for waking in clock[tick]:
            a[i] = waking
            i += 1
function sleepSort(a) {
  if (a.length === 0) return;
  const top = Math.max(...a);
  const clock = Array.from({ length: top + 1 }, () => []);
  for (const value of a) clock[value].push(value);
  let at = 0;
  for (let tick = 0; tick <= top; tick++) {
    for (const waking of clock[tick]) a[at++] = waking;
  }
}
void sleep_sort(int a[], int n) {
    int top = 0;
    for (int i = 0; i < n; i++) {
        if (a[i] > top) top = a[i];
    }
    int* first = malloc(sizeof(int) * (top + 1));
    int* next = malloc(sizeof(int) * (n + 1));
    for (int tick = 0; tick <= top; tick++) first[tick] = -1;
    for (int i = 0; i < n; i++) {
        next[i] = first[a[i]];
        first[a[i]] = i;
    }
    int at = 0;
    for (int tick = 0; tick <= top; tick++) {
        for (int s = first[tick]; s >= 0; s = next[s]) a[at++] = tick;
    }
    free(first);
    free(next);
}
void sleep_sort(std::vector<int>& a) {
    if (a.empty()) return;
    int top = *std::max_element(a.begin(), a.end());
    std::vector<std::vector<int>> clock(top + 1);
    for (int value : a) clock[value].push_back(value);
    size_t at = 0;
    for (int tick = 0; tick <= top; tick++) {
        for (int waking : clock[tick]) a[at++] = waking;
    }
}
static void SleepSort(int[] a) {
    if (a.Length == 0) return;
    int top = a.Max();
    var clock = new List<int>[top + 1];
    for (int tick = 0; tick <= top; tick++) clock[tick] = new List<int>();
    foreach (int value in a) clock[value].Add(value);
    int at = 0;
    for (int tick = 0; tick <= top; tick++) {
        foreach (int waking in clock[tick]) a[at++] = waking;
    }
}
static void sleepSort(int[] a) {
    if (a.length == 0) return;
    int top = Arrays.stream(a).max().getAsInt();
    List<List<Integer>> clock = new ArrayList<>();
    for (int tick = 0; tick <= top; tick++) clock.add(new ArrayList<>());
    for (int value : a) clock.get(value).add(value);
    int at = 0;
    for (int tick = 0; tick <= top; tick++) {
        for (int waking : clock.get(tick)) a[at++] = waking;
    }
}
돌려 보고 코드도 본다