UNIHIVE

Study Hub UNIPORT CSC 282

CSC 282 · Database Programming

Searching, sorting and retrieval

Linear and binary search, indexes, sorting records, and producing reports with totals.

Our notes

1 min read

Linear search

Look at each record in turn until found. Works on any file. Average n/2 comparisons, worst n.

Binary search

Needs records sorted on the key. Compare with the middle record; discard the half that cannot contain the key; repeat.
At most about log₂ n comparisons: for 1,000,000 records, about 20.

Worked example

Sorted keys: 12, 19, 25, 31, 44, 52, 60, 73, 88 (positions 1 to 9). Find 60.

  1. Low 1, high 9, middle 5 → 44 < 60, so low = 6.
  2. Low 6, high 9, middle 7 → 60. Found in 2 comparisons. (A linear search needs 7.)

In code (positions from 0):

    def binary_search(keys, target):
        low, high = 0, len(keys) - 1
        while low <= high:
            mid = (low + high) // 2
            if keys[mid] == target:
                return mid
            if keys[mid] < target:
                low = mid + 1
            else:
                high = mid - 1
        return -1

Indexes

An index is a separate sorted list of key values with the location of each record, like the index of a textbook. Searching the index is fast, then one read fetches the record. Databases build indexes on primary keys automatically; you can add them on fields often searched (Surname, Department). Indexes speed reading but slow inserts and updates slightly, and take space.

Sorting

Arranging records by one or more keys: by Department, then Surname within department. Common in-memory methods are insertion sort, merge sort and quicksort; very large files are sorted in pieces and merged (external sort). In SQL you simply write ORDER BY.

Retrieval and reports

A report pulls the records you need (selection), the fields you need (projection), in the order you need, with totals.
Control break report: records sorted by department; when the department changes, print the sub-total and start a new one; at the end print the grand total.

DepartmentStudentsFees owed (₦)
Computer Science3120,000
Physics245,000
Total5165,000

Exams usually ask

  • Trace a binary search and count comparisons.
  • Explain an index and when to add one.
  • Design a control-break report.

Common mistake

Running a binary search on unsorted data. It can miss a record that is there; sort first or use a linear search.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

Read

Watch

We link to free material and never copy it. Every link was opened by our team before it went up; video data is a rough guide at 360p.

All CSC 282 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.