Fixing Bubble Sort Failures in Transaction Histories (account type sorting)

Summary

The sorting routine fails to reorder the globalTransHistory list because the comparison logic is applied to raw strings rather than parsed account types. This results in a partially sorted or unchanged list, causing the UI to display random entries.

Root Cause

  • Using compareTo on unsanitized string fragments that still contain the prefix account type:
  • String concatenation order is reversed after a swap, breaking the bubble sort invariant
  • The loop condition uses HistoryManager.globalTransHistory.size() - 1 which becomes stale after modifications
  • Missing null‑check for entries that may not split into two parts, leading to skipped comparisons ## Why This Happens in Real Systems
  • Legacy code often stores structured data as delimited strings for simplicity
  • Engineers assume that substring extraction is safe without validating length
  • Performance‑oriented sorting is sometimes implemented inline without testing edge cases

Real-World Impact

  • Incorrect transaction display leads to user confusion and audit failures

  • Repeated sorting attempts can cause performance degradation due to repeated full passes

  • Data integrity issues may propagate to downstream reporting modules

  • Sorting anomalies can hide bugs in related features such as balance calculations

  • Debugging cycles increase, wasting valuable engineering time

  • Consistent failure may erode trust in the codebase among stakeholders

Example or Code

// Correct bubble sort for transaction history sorted by account type
List history = HistoryManager.globalTransHistory;
int n = history.size();
for (int i = 0; i < n - 1; i++) {
    for (int j = 0; j  0) {
            // swap entries safely            history.set(j, entry2);
            history.set(j + 1, entry1);
        }
    }
}
System.out.println("\n======= TRANSACTION HISTORY =======");
history.forEach(System.out::println);
System.out.println("===================================\n");

How Senior Engineers Fix It

  • Parse and validate the split result before accessing elements – Extract the sortable key (account type) once and store it to avoid repeated string operations
  • Use type‑safe collections or a custom Transaction object instead of raw strings
  • Apply unit tests covering edge cases such as empty entries or malformed records
  • Prefer Collections.sort with a comparator for clarity and correctness

Why Juniors Miss It

  • Overfocus on syntax rather than data semantics – Lack of experience with string manipulation edge cases (e.g., missing delimiters)
  • Tendency to copy‑paste algorithms without adapting them to the domain model
  • Limited exposure to debugging strategies that involve stepping through loops and inspecting intermediate values

Leave a Comment