Sorted List (ADT)

Context: FIT1008_MOC · a List (ADT) under a sort Invariant · backbone clustering its SortedArrayList implementation · the motivation for a balanced Binary Tree

Quick Revision

  • 🎯 Objective: list kept in value order ➔ fast search, but user loses position choice (append/insert → add).
  • 📦 Core Components: Contractadd + faster index | SortedArrayListBinary Search search, shift-on-insert.
  • ⚡ Key Constraint: array gives search but insert (shift) ➔ for both needs a balanced Binary Tree.

📝 Core

1. Sorted List Contract (Sort Invariant)

  • Sort invariant ➔ a List (ADT) whose elements stay in increasing order (Invariant).
  • Op remapappend/insert/__setitem__ meaningless ➔ replaced by a single add.
  • Not a List subclass ➔ would break the List contract (insert(i,x) demands arbitrary placement) ➔ shared fields ≠ “is-a”.

2. SortedArrayList (Array-Backed)

  • Storage substrate ➔ fixed Array (Data Structure) + length, elements increasing.
  • Distinctive opsindex via Binary Search () | add = find slot + shift .
  • Shift dominatesadd is unless the item belongs at the very end.

⚙️ Core Implementation

🔹 SortedArrayList — binary-search index, shift-on-add

⚖️ Core Decision Matrix

Variant / Strategyindex (search)addOrdered iterationCache / Note
SortedArrayList (Binary Search) find + shiftrandom access enables binary search
sorted linked list (no random access) find + splicefast splice, can’t binary-search
balanced BSTonly one for both

When It Flips: the array can't make add cheap ( find but shift); the sorted linked list is the inverse (slow find, fast splice). Only a balanced Binary Tree links a node in place ➔ insert and search.

📊 Exam Execution Trace

Manual Execution Trace

add(15) into [4, 8, 23, 42]:

Step / StateTrigger OpActionArray Payload
0 (Init)startadd 15[4, 8, 23, 42]
1binary-search slotconverge → index 2(between 8 and 23)
2make-space (shift)23,42 moved ()[4, 8, _, 23, 42]
3placelength += 1[4, 8, 15, 23, 42]

Applied Exercise

Problem: Show why add is despite an search. Derivation Proof / Hand-Calculation Walkthrough:

Final Extracted Output: add in general — the contiguous-block shift, not the search, is the bottleneck.

🧠 Active Recall