-
-
Save sricharankrishnan/08a538b2ca47af3bc9395036c209eb76 to your computer and use it in GitHub Desktop.
A queue (array based) data structure implementation done in java along with respective time complexities for each method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Queue Data Structure (Array Based Implementation) | |
* | |
* Enqueue: O(1) | |
* Dequeue: O(n) | |
* Peek: O(1) | |
* Search: O(n) | |
*/ | |
import java.util.*; | |
public class ArrayQueue<E> { | |
private static final int DEFAULT_CAPACITY = 5; | |
private int capacity; | |
private int size; | |
private Object[] elements; | |
public ArrayQueue() throws Exception { | |
this(ArrayQueue.DEFAULT_CAPACITY); | |
} | |
public ArrayQueue(int capacity) throws Exception { | |
if (capacity <= 0) { | |
throw new Exception("Cannot intialize. Capacity to be greater than zero"); | |
} | |
else { | |
this.capacity = capacity; | |
this.size = 0; | |
this.elements = new Object[capacity]; | |
} | |
} | |
/* O(1) */ | |
public E peek() { | |
return (this.isEmpty()) ? null : (E) this.elements[0]; | |
} | |
/* O(1) */ | |
public void enqueue(E value) { | |
if (!Objects.isNull(value) && !this.isFull()) { | |
this.elements[this.size++] = value; | |
} | |
} | |
/* O(n) */ | |
public E dequeue() { | |
if (this.isEmpty()) { | |
return null; | |
} | |
E value = (E) this.elements[0]; | |
for (int i = 0; i < this.size - 1; ++i) { | |
this.elements[i] = this.elements[i + 1]; | |
} | |
this.elements[this.size - 1] = null; | |
--this.size; | |
return value; | |
} | |
/* O(n) */ | |
public int search(E value) { | |
int index = -1; | |
if (!this.isEmpty() && !Objects.isNull(value)) { | |
for (int i = 0; i < this.size; ++i) { | |
if ((E) this.elements[i] == value) { | |
index = i; | |
break; | |
} | |
} | |
} | |
return index; | |
} | |
public int size() { | |
return this.size; | |
} | |
public boolean isFull() { | |
return this.size == this.capacity; | |
} | |
public boolean isEmpty() { | |
return this.size == 0; | |
} | |
public String toString() { | |
String string = "["; | |
for (int i = 0; i < this.size; ++i) { | |
string += (i == this.size - 1) ? this.elements[i] : this.elements[i] + ", "; | |
} | |
return string += "]"; | |
} | |
public static void main(String[] args) throws Exception { | |
/* remove this comment and see how this works | |
ArrayQueue queue = new ArrayQueue(); | |
queue.enqueue(12); | |
queue.enqueue(123); | |
queue.enqueue(4); | |
queue.enqueue(11); | |
queue.enqueue(23); | |
System.out.println("Search: " + queue.search(23)); | |
System.out.println(queue); | |
*/ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment