AP Computer Science A · Topic 7.6

Sorting Practice

Part of ArrayList.

Practice questions

33

Want a predicted score for the whole AP CSA exam? Take the 20-question diagnostic and Lumi will plan the rest.

Sample questions

5 of 33 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. Sample 1difficulty 2/5

    public class Item implements Comparable<Item> {
        private int v;
        public Item(int x) { v = x; }
        public int compareTo(Item o) {
            if (v < o.v) return -1;
            if (v > o.v) return 1;
            return 0;
        }
    }
    // Usage:
    Item a = new Item(5);
    Item b = new Item(5);
    System.out.print(a.compareTo(b));

    What is printed?

    • A

      -1

    • B

      5

    • C

      1

    • D

      0

      check_circle

    Why

    Equal values lead to compareTo returning 0. This is a valid (and safer) compareTo implementation that avoids overflow.

  2. Sample 2difficulty 2/5

    String a = "cat";
    String b = "cat";
    int r = a.compareTo(b);

    What is r?

    • A

      3

    • B

      0

      check_circle
    • C

      1

    • D

      -1

    Why

    Equal strings yield 0 from compareTo.

  3. Sample 3difficulty 2/5

    String a = "apple";
    String b = "banana";
    int r = a.compareTo(b);

    What is true about r?

    • A

      r is 1 always

    • B

      r == 0

    • C

      r > 0

    • D

      r < 0

      check_circle

    Why

    "apple" precedes "banana" lexicographically, so compareTo returns a negative value.

  4. Sample 4difficulty 2/5

    int[] a = {7, 3, 9, 1, 5};
    java.util.Arrays.sort(a);
    int median = a[a.length / 2];

    What is median?

    • A

      3

    • B

      9

    • C

      5

      check_circle
    • D

      7

    Why

    Sorted: {1,3,5,7,9}; index 2 is 5, the median.

  5. Sample 5difficulty 2/5

    ArrayList<String> list = new ArrayList<String>();
    list.add("banana");
    list.add("apple");
    list.add("cherry");
    // After Collections.sort(list):
    System.out.print(list.get(0));

    What is printed?

    • A

      Compile error: String not Comparable

    • B

      banana

    • C

      cherry

    • D

      apple

      check_circle

    Why

    String implements Comparable<String> using lexicographic order. After sorting, "apple" comes first.

AP Computer Science A · 7.6 Sorting — Practice Questions | Acemy