기본 콘텐츠로 건너뛰기

[DATA STRUCTURE] HEAP

What is Binary Heap?
Let us first define a Complete Binary Tree. A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible (Source Wikipedia)

Binary Heap is a Complete Binary Tree where items are stored in a special order such that value in a parent node is greater(or smaller) than the values in its two children nodes. The former is called as max heap and the latter is called min heap. The heap can be represented by binary tree or array.

Why array based representation for Binary Heap?
Since a Binary Heap is a Complete Binary Tree, it can be easily represented as array and array based representation is space efficient. If the parent node is stored at index I, the left child can be calculated by 2 * I + 1 and right child by 2 * I + 2 (assuming the indexing starts at 0).

public class HeapSort {

    void sort(int[] arr) {
        int n = arr.length;

        for (int i = n / 2 - 1i >= 0i--) {
            System.out.println(i);
            maxHeapify(arrni);
        }
        // One by one extract an element from heap
        for (int i = n - 1i > 0i--) {
            // Move current root to end
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;

            // call max heapify on the reduced heap
            maxHeapify(arri0);
        }

    }

    private void maxHeapify(int[] arrint nint i) {
        int largest = i;
        int left = 2 * i + 1;
        int right = 2 * i + 2;

        if (left < n && arr[left] > arr[largest]) {
            largest = left;

        }
        if (right < n && arr[right] > arr[largest]) {
            largest = right;

        }
        if (largest != i) {
            int swap = arr[i];
            arr[i] = arr[largest];
            arr[largest] = swap;

            maxHeapify(arrnlargest);
        }

    }

    private void smallHeapify(int[] arrint nint i) {
        int smallest = i;
        int left = 2 * i + 1;
        int right = 2 * i + 2;

        if (left < n && arr[left] < arr[smallest]) {
            smallest = left;
        }
        if (right < n && arr[right] < arr[smallest]) {
            smallest = right;
        }
        if (smallest != i) {
            int swap = arr[i];
            arr[i] = arr[smallest];
            arr[smallest] = swap;

            smallHeapify(arrnsmallest);
        }
    }

    static void printArray(int arr[]) {
        int n = arr.length;
        for (int i = 0i < ni++) {
            System.out.println(arr[i] + " ");
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int arr[] = { 121113567 };
        int n = arr.length;

        HeapSort h = new HeapSort();
        h.sort(arr);
        System.out.println("Sorted array is");
        printArray(arr);
    }

}


REFERENCE

https://www.geeksforgeeks.org/heap-sort/

댓글

이 블로그의 인기 게시물

[DATA STRUCTURE] 큐 QUEUE

큐[QUEUE]의개념 Queue is an abstract data structure, somewhat similar to Stacks.  Unlike stacks, a queue is open at both its ends. One end is always used to insert data (enqueue) and the other is used to remove data (dequeue).  Queue follows First-In-First-Out methodology, i.e., the data item stored first will be accessed first. First In First Out Basic Operation Queue operations may involve initializing or defining the queue, utilizing it, and then completely erasing it from the memory. Here we shall try to understand the basic operations associated with queues − enqueue() − add (store) an item to the queue. dequeue() − remove (access) an item from the queue. Few more functions are required to make the above-mentioned queue operation efficient. These are − peek() − Gets the element at the front of the queue without removing it. isfull() − Checks if the queue is full.[Boolean] isempty() − Checks if the queue is empty.[Boolean] 큐의사용 예 너비 우선 탐색(BFS, Breadth-First Search) 구현 처리해야 할 노...

SSH 공개키 암호화 설정

★서버명은 임의 공개키 암호화 방식 -[bigdata01,02,03,04]에 동시에 만듬 1.ssh key 만들기 [ ssh-keygen -t rsa ] 2. 아래와 같이 key 생성여부 확인 3. [ cat id_rsa.pub >> authorized_keys ] authorized_keys폴더에 key 암호를 복사   4.폴더 확인 id_rsa [private] 와 id_rsa.pub [public] 이 만들어짐 5 cat authorized_keys 로 검색하면 아래와 같이 암호가 만든 폴더로 들어감. 6.bigdata01에  [ ssh root@bigdata02 cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys ] 를 입력 7.최종적으로 bigdata 02,03,04를 6번 같이 입력하여 authorized_keys 폴더 에 전부 넣음 8. [ scp -rp authorized_keys root@bigdata02:~/.ssh/authorized_keys ]  ★scp= secure copy bigdata 02, 03, 04 설정한 것을 복사해서 보냄. 9. bidata01에서 [ ssh bigdata02 date ] 코드를 쳐서 아래와 같이 나오면 성공