// Program to test solutions to problem #4 on the cse143x final, fall 2021. // Fill in your solution to isSorted, then compile and run the program. import java.util.*; public class FinalTest4 { public static boolean isSorted(Stack s) { // fill in your solution here // you can also rename the parameter above } // this is the sample solution public static boolean isSorted2(Stack s) { if (s.size() <= 1) { return true; } else { Queue q = new LinkedList<>(); int prev = s.pop(); q.add(prev); boolean ok = true; while (!s.isEmpty()) { int next = s.pop(); if (prev < next) { ok = false; } q.add(next); prev = next; } while (!q.isEmpty()) { s.push(q.remove()); } while (!s.isEmpty()) { q.add(s.pop()); } while (!q.isEmpty()) { s.push(q.remove()); } return ok; } } private static int failCount; public static void main(String[] args) { int[] data = {-5, 0, 3, 18, 18, 18, 23, 42, 208, 17, 20, 94}; Stack s = new Stack(); test(s); for (int n : data) { s.push(n); test(s); } if (failCount == 0) { System.out.println("all tests passed"); } else { System.out.println("failed " + failCount + " tests"); } } public static void test(Stack s) { System.out.println("stack = " + s); boolean test1 = isSorted2(s); System.out.println("isSorted = " + test1); boolean fail = false; try { Stack s2 = new Stack(); for (int n : s) { s2.push(n); } boolean test2 = isSorted(s2); if (test1 != test2) { fail = true; System.out.println("yours = " + test2); if (!s.equals(s2)) { fail = true; System.out.println("yours left stack = " + s2); } } } catch (RuntimeException e) { int line = e.getStackTrace()[0].getLineNumber(); System.out.println(" threw " + e + " at line #" + line); fail = true; } if (fail) { System.out.println("failed"); failCount++; } else { System.out.println("passed"); } System.out.println(); } }