PriorityQueue(by Array) 구현 코드

한시삼십사분·2022년 1월 20일

자료구조 JAVA

목록 보기
15/16
post-thumbnail

Queue Interface

package Interface_form;

public interface Queue<E> {
	
	/**
	 * 
	 * @param data queue에 추가할 요소
	 * @return 정상적으로 추가되었을 때 true 반환
	 */
	boolean offer(E data);
	
	/**
	 * queue의 첫번 째 요소를 삭제하고 해당 요소를 반환
	 * @return queue의 첫번 째 요소
	 */
	E poll();
	
	/**
	 *	queue의 첫번 째 요소를 삭제하지 않고 반환
	 * @return Queue의 첫번 쨰 요소
	 */
	E peek();
}

PriorityQueue Class

import java.util.Comparator;
import java.util.NoSuchElementException;

import Interface_form.Queue;

public class PriorityQueue<E> implements Queue<E> {
	private final Comparator<? super E> comparator;
	private static final int DEFAULT_CAPACITY = 10;
	
	private int size;
	private Object[] array;
	
	public PriorityQueue() {
		this(null);
	}
	
	public PriorityQueue(Comparator<? super E> comparator) {
		this.array = new Object[DEFAULT_CAPACITY];
		this.size = 0;
		this.comparator = comparator;
	}
	
	public PriorityQueue(int capacity, Compartor<? super E> comparator) {
		this.array = new Object[capacity];
		this.size = 0;
		this.comparator = comparator;
	}
	
	private int getParent(int index) {
		return index / 2;
	}
	
	private int getLeftChild(int index) {
		return index * 2; 
	}
	private int getRightChild(int index) {
		return index * 2 + 1;
	}
	
	private void resize(int newCapacity) {
		Object[] newArray = new Object[newCapacity];
		
		for(int i=0; i<=size; i++) {
			newArray[i] = this.array[i];
		}
		
		this.array = null;
		this.array = newArray;
	}
	
	@Override
	public boolean offer(E value) {
			
		if(size + 1 == array.length) {
			resize(array.length * 2);
		}
			
		siftUp(size + 1, value);	
		size++;	
		return true;
	}
		
	
	private void siftUp(int idx, E target) {
	
		if(comparator != null) {
			siftUpComparator(idx, target, comparator);
		}
		else {
			siftUpComparable(idx, target);
		}
	}
	 
	@SuppressWarnings("unchecked")
	private void siftUpComparator(int idx, E target, Comparator<? super E> comp) {
			
		while(idx > 1) {
			int parent = getParent(idx);	 
			Object parentVal = array[parent];	
			
			if(comp.compare(target, (E) parentVal) >= 0) {
				break;
			}
			array[idx] = parentVal;
			idx = parent;
		}
		array[idx] = target;
	}
		
		
	@SuppressWarnings("unchecked")
	private void siftUpComparable(int idx, E target) {
			
		Comparable<? super E> comp = (Comparable<? super E>) target;
	
		while(idx > 1) {
			int parent = getParent(idx);
			Object parentVal = array[parent];
			
			if(comp.compareTo((E)parentVal) >= 0) {
				break;
			}
			array[idx] = parentVal;
			idx = parent;
		}
		array[idx] = comp;
	}
	
	// poll methods
	@Override
	public E poll() {
		if(array[1] == null) {
			return null;
		}
		return remove();
	}
		
	@SuppressWarnings("unchecked")
	public E remove() {
		if(array[1] == null) {	
			throw new NoSuchElementException();
		}	
			
		E result = (E) array[1];	
		E target = (E) array[size];	
			
		array[size] = null;
		size--;		
		siftDown(1, target);	
			
		return result;
	}
		
	
	private void siftDown(int idx, E target) {
		if(comparator != null) {
			siftDownComparator(idx, target, comparator);
		}
		else {
			siftDownComparable(idx, target);
		}
	}
		
	@SuppressWarnings("unchecked")
	private void siftDownComparator(int idx, E target, Comparator<? super E> comp) {
	 
		array[idx] = null;
		
		int parent = idx;	
		int child;	
		while((child = getLeftChild(parent)) <= size) {
			
			int right = getRightChild(parent);
			Object childVal = array[child];	
	 
			
			if(right <= size && comp.compare((E) childVal, (E) array[right]) > 0) {
				child = right;
				childVal = array[child];
			}
				
			if(comp.compare(target ,(E) childVal) <= 0){
				break;
			}
				
			
			array[parent] = childVal;
			parent = child;
	 
		}
			
		array[parent] = target;
	    
		if(array.length > DEFAULT_CAPACITY && size < array.length / 4) {
			resize(Math.max(DEFAULT_CAPACITY, array.length / 2));
		}
		
	}
	
	private void siftDownComparable(int idx, E target) {
		
		Comparable<? super E> comp = (Comparable<? super E>) target;
			
		array[idx] = null;
		size--;
			
		int parent = idx;
		int child;
	 
		while((child = getLeftChild(parent)) <= size) {
				
			int right = getRightChild(parent);
				
			Object childVal = array[child];
			
			if(right <= size && ((Comparable<? super E>)childVal).compareTo((E)array[right]) > 0) {
				child = right;
				childVal = array[child];
			}
				
			if(comp.compareTo((E) childVal) <= 0){
				break;
			}
			array[parent] = childVal;
			parent = child;
				
		}
		array[parent] = comp;
			
		if(array.length > DEFAULT_CAPACITY && size < array.length / 4) {
			resize(Math.max(DEFAULT_CAPACITY, array.length / 2));
		}
			
	}
	
	
	public int size() {
		return size;
	}
	
	@SuppressWarnings("unchecked")
	public E peek() {
		if(array[1] == null) {
			throw new NoSuchElementException();
		}
		return (E) array[1];
	}
	
	public boolean isEmpty() {
		return size() == 0;
	}
	
	public boolean contains(Object data) {
		for(int i=0; i<=size; i++) {
			if(array[i].equals(data)) {
				return true;
			}
		}
		
		return false;
	}
	
	public void clear() {
		for(int i=0 ; i<=size ; i++) {
			array[i] = null;
		}
		size= 0;
	}

}

https://st-lab.tistory.com/161?category=856997
내가 직접 코딩해보고 사이트를 확인하여 수정하는 방법으로 구현을 진행했음

profile
인간은 망각의 동물이라지만 이건 너무한 거 아니냐고

0개의 댓글