In java by using this Queue class: public class Queue { private int rear, front; private Object[] elements; Queue(int capacity) { elements = new Object[capacity]; rear = -1; front = 0; } void enqueue(Object data) { if (isFull()) { System.out.println("Queue overflow"); } else { rear = (rear + 1) % elements.length; elements[rear] = data; } } Object dequeue() { if (isEmpty()) { System.out.println("Queue empty"); return null; } else { Object retData = elements[front]; elements[front] = null; front = (front + 1) % elements.length; return retData; } } Object peek() { if (isEmpty()) { System.out.println("Queue is empty"); return null; } else { return elements[front]; } } boolean isEmpty() { return elements[front] == null; } boolean isFull() { return (front == (rear + 1) % elements.length && elements[front] != null && elements[rear] != null); } int size() { if (rear >= front) { return rear - front + 1; } else if (elements[front] != null) { return elements.length - (front - rear) + 1; } else { return 0; } } void majorityElement() { int majorcount = 0; int n = size(); Object major = elements[front]; for (int i = front; i <= rear; i++) { int count = 0; Object p = elements[i]; for (int j = 0; j <= rear; j++) { Object c = elements[j]; if (p.equals(c)) { count++; } } if (count > majorcount) { majorcount = count; major = p; } } if (majorcount > (n / 2)) { System.out.println(" major element is " + major); } else { System.out.println(" no major element found"); } } }
In java
by using this Queue class:
public class Queue {
private int rear, front;
private Object[] elements;
Queue(int capacity) {
elements = new Object[capacity];
rear = -1;
front = 0;
}
void enqueue(Object data) {
if (isFull()) {
System.out.println("Queue overflow");
} else {
rear = (rear + 1) % elements.length;
elements[rear] = data;
}
}
Object dequeue() {
if (isEmpty()) {
System.out.println("Queue empty");
return null;
} else {
Object retData = elements[front];
elements[front] = null;
front = (front + 1) % elements.length;
return retData;
}
}
Object peek() {
if (isEmpty()) {
System.out.println("Queue is empty");
return null;
} else {
return elements[front];
}
}
boolean isEmpty() {
return elements[front] == null;
}
boolean isFull() {
return (front == (rear + 1) % elements.length &&
elements[front] != null && elements[rear] != null);
}
int size() {
if (rear >= front) {
return rear - front + 1;
} else if (elements[front] != null) {
return elements.length - (front - rear) + 1;
} else {
return 0;
}
}
void majorityElement() {
int majorcount = 0;
int n = size();
Object major = elements[front];
for (int i = front; i <= rear; i++) {
int count = 0;
Object p = elements[i];
for (int j = 0; j <= rear; j++) {
Object c = elements[j];
if (p.equals(c)) {
count++;
}
}
if (count > majorcount) {
majorcount = count;
major = p;
}
}
if (majorcount > (n / 2)) {
System.out.println(" major element is " + major);
} else {
System.out.println(" no major element found");
}
}
}
Step by step
Solved in 4 steps