Skip to content

Instantly share code, notes, and snippets.

@sricharankrishnan
Created January 16, 2023 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sricharankrishnan/08a538b2ca47af3bc9395036c209eb76 to your computer and use it in GitHub Desktop.
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
/**
* 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