Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package kopiec;
- public class Heap {
- int left;
- int right;
- int heap[];
- int n;
- int smaller;
- int heapSize;
- public Heap(int size){
- heapSize = 0;
- heap = new int[size];
- }
- public void buildingHeap(int[] heap){
- n = heap.length-2;
- for(int i =n/2; i>=0;i--){
- findMinimum(i);
- }
- }
- public void findMinimum(int i){
- left = 2*i+1;
- right = 2*i+2;
- if (left<= n+1 && heap[left] < heap[i])
- smaller = left;
- else
- smaller = i;
- if (right <= n+1 && heap[right] < heap[i])
- if(heap[smaller]>heap[right])
- smaller = right;
- if (smaller != i){
- swap(i,smaller);
- findMinimum(smaller);
- }
- }
- public void swap(int i, int j){
- int tmp = heap[i];
- heap[i] = heap[j];
- heap[j] = tmp;
- }
- public void heapSort(int [] tab){
- heap=tab;
- buildingHeap(heap);
- for(int i=n+1;i>0;i--) {
- swap(0,i);
- n=n-1;
- findMinimum(0);
- }
- }
- public void enqueue(int value){
- int i=0;
- heapSize++;
- // if(heap.length==0)
- // heap=biggerHeap();
- heap=biggerHeap();
- i=heap.length-1;
- heap[i]=value;
- while(heap[(i-1)/2]>heap[i]){
- int x=heap[(i-1)/2];
- heap[(i-1)/2]=heap[i];
- heap[i]=x;
- i=(i-1)/2;
- }
- }
- private int []biggerHeap(){
- int []heap1=new int[heap.length+1];
- System.arraycopy(heap,0,heap1,0,heap.length);
- return heap1;
- }
- public void heapDisplay(){
- for(int i=0;i<heap.length;i++)
- System.out.print(heap[i]+", ");
- System.out.println();
- }
- public void newHeapDisplay(){
- for(int i=0;i<heapSize;i++)
- System.out.print(heap[i]+", ");
- System.out.println();
- }
- public int dequeue(){
- int tmp = heap[0];
- swap(0,heap.length-1);
- heapSize--;
- buildingHeap(heap);
- return tmp;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment