I'm creating a method to test if a given stack is sorted or not. I've completed the main task of the program but is there a way to implement this algorithm without having O(N^2). I would like to get this one with O(N). Does such a solution exist? If so can someone point me in the right direction.
Some rules - Only one auxiliary stack can be made. - No additional data structures. - If a stack is empty or has one item it is assumed to be sorted. - Must perform in O(N)
public static boolean isSorted(Stack s){ boolean sorted = true; Stack backup = new Stack(); int prev, curr; if(s.isEmpty() || s.size() == 1) { sorted = true; } else { while(!s.isEmpty()){ prev = s.pop(); backup.push(prev); curr = s.pop(); backup.push(curr); if(prev > curr && sorted) sorted = false; } } while(!backup.isEmpty()) { s.push(backup.pop()); } return sorted; } Sample Input: {20,20,17,11,9,8,3,2}
Output:
top 2 3 8 9 11 17 20 20 bottom | isSorted = true | top 2 3 8 9 11 17 20 20 bottom At the end of the function. The stack given should be in its original state. I just have to get this in O(N)
pushto flip a flag from sorted to unsorted if it sees a value out of line. No computation required after that. O(1) after all those little comparison costs are amortized in.