What are the big o notation for this code below. I still couldn't grasp the concept fully. I am supposed to get a thought from experienced coders to give a summary for the big o performance based on this code.
import java.util.*;
import java.util.InputMismatchException;
import javax.swing.*;
public class MyStack {
private int maxSize;
private long[] stackArray;
private int top;
public MyStack(int s) {
maxSize = s;
stackArray = new long[maxSize];
top = -1;
}
public void push(long j) {
stackArray[++top] = j;
System.out.println("Push onto stack");
}
public long pop() {
return stackArray[top--];
}
public long peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
public static void main(String[] args) {
Scanner num = new Scanner(System.in);
int input =0;
int x;
MyStack theStack = new MyStack(5);
for(x=0; x<5; x++)
{
System.out.println("\nEnter a number(Push): ");
input = num.nextInt();
theStack.push(input);
}
System.out.print("The first element on the top is the top of the stack");
System.out.println("");
while (!theStack.isEmpty()) {
long value = theStack.pop();
System.out.print(value);
System.out.println(" Pop");
}
System.out.println("");
}
}
Data structure complexity of an operation is always calculated against the number of element it holds, is shows maximum time it will take with the increase the number of elements.
Eg : How much time will it take to search an element in "B-Tree" given that there exists n number of elements already in it.
In B-Tree search time is O(log n), means that the maximum search time will grow as a function of log n (see the Big-O Complexity graph).
In your case to implement the stack you have used an array and you have multiple oprations, but your operations does not depend on the element which carry in your stack, because complexity of get an element in a specific location is O(1). So all your operation takes O(1) time.
push - O(1)
pop - O(1)
isFull - O(1)
isEmpty - O(1)
But if you implement search in your stack, check whether given long is in your stack then the search depends on the elements where you have to iterate all the elements and the complexity will be O(n).