2017년 2월 7일 화요일

연결 리스트의 퀵정렬 (Quick sort on Singly Linked List)

연결 리스트에서의 퀵정렬 역시 배열에서의 퀵정렬과 동일한 방식으로, 주어진 데이터를 두 개로 partition하고 각각의 영역을 다시 퀵정렬한 후에 연결을 하는 방법으로 구현한다.
연결 리스트를 partition하는 것과 정렬된 sub linked list를 하나의 연결 리스트로 합치는 과정만 조금 다르다.

func QuickSort(root *Node) *Node {
    if root == nil {
        return nil
    }
    small, pivot, large := partition2(root)
    small = QuickSort(small)
    large = QuickSort(large)

    pivot.Next = large
    var newRoot *Node
    if small == nil {
        newRoot = pivot
    } else {
        newRoot = small
        lastSmall := getLast(small)
        lastSmall.Next = pivot
    }
    return newRoot
}

func partition(root *Node) (*Node, *Node, *Node) {
    var small, large *Node
    node := root.Next
    for node != nil {
        next := node.Next
        if node.Val < root.Val {
            node.Next = small
            small = node
        } else {
            node.Next = large
            large = node
        }
        node = next
    }
    root.Next = nil

    return small, root, large
}

댓글 없음:

댓글 쓰기

잔돈 만드는 방법 (Coin change)

숫자(N)와 숫자의 집합(C = {C1, C2, C3, ...}이 주어졌을 때, C의 숫자들을 중복으로 사용하여 N을 만드는 방법의 수를 구해보자.  잔돈 문제로 바꾸어서 표현하면, 각각 값어치가 C1, C2, C3, ... 인 동전이 무한대로 주어질...