Language/Javascript

    [Javascript] 힙 정렬(Heap sort) - min heap 구현

    // min heap // n: parent , 2*n+1 : left child, 2*n+2 : right child class Heap { constructor() { this.heap = [] } swap(a, b) { [this.heap[a], this.heap[b]] = [this.heap[b] , this.heap[a]] } size() { return this.heap.length } print() { console.log(this.heap) } push(value) { let idx, parent = 0 this.heap.push(value) idx = this.heap.length-1 parent = Math.floor((idx-1)/2) while(this.heap[parent] > v..

    [Javascript] 힙 정렬(Heap sort) - max heap 구현

    // max heap // n : parent, 2*n+1 : left child, 2*n+2: right child class Heap { constructor() { this.heap = [] } swap(a, b) { // 구조분해 할당 문법으로 swap 가능 [this.heap[a], this.heap[b]] = [this.heap[b], this.heap[a]] } size() { return this.heap.length } push(value) { // 맨뒤에 추가 max heap 이므로 부모랑 비교해서 큰값을 부모랑 swap 해줘야함 this.heap.push(value) let idx = this.heap.length-1 let parent = Math.floor((idx-1)/2) wh..

    [Javascript] sort() 동작 방식 (내부 알고리즘)

    일단 sort 에 대해서 정확한 이해가 필요하다고 생각하여 글을 쓰게 되었음. 뭔가 정리를 안해놓으면 또 까먹을거같아서.. 찾아보다가 좋은 글이 있어서 퍼왔는데 이분이 설명을 잘해놓은듯함. 구체적인 정렬 알고리즘은 프로그래밍 초심자가 이해하기 어려워서 이고잉님께서 일부러 설명을 스킵하신 것 같은데... 밑에 잘못된 정보가 있어 제가 굳이 설명을 보탭니다. 우선 [20, 10, 9,8,7,6,5,4,3,2,1]의 배열에서 a-b라는 연산을 모두 한 다음 그 결과값으로 정렬하는 것이 결코 아닙니다. 뭐하러 굳이 뺄셈을 하고 그 값으로 또 정렬하겠습니까? 자바스크립트의 정확한 알고리즘은 아니지만 쉽게 정렬 알고리즘을 설명하면 이렇습니다. (a,b) 형식으로 지정한 두 인자를 차례로 비교합니다. 우선 배열 nu..