Docsity

CS 161 — Sorting and Searching Algorithms, Exams of Nursing

Toggle sidebar
bg1
CS 161 — Sorting and Searching
Algorithms
Table of Contents
1. Searching Fundamentals
2. Linear Search
3. Binary Search
4. InsertionSort
5. MergeSort
6. QuickSort
7. Heapsort
8. Selection Algorithms
9. Comparison-Sort Lower Bound
10. Algorithm Comparison
11. Official CS 161 References
Searching Fundamentals
A search algorithm determines whether a target value appears in a collection and, often, returns
its position.
The appropriate algorithm depends on whether the data is sorted:
Unsorted data: use linear search.
Sorted data: use binary search for fast lookup.
Searching is closely connected to sorting because sorting enables faster repeated
searches.web.stanford+1
Linear Search
Linear search scans an unsorted array from beginning to end.
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download CS 161 — Sorting and Searching Algorithms and more Exams Nursing in PDF only on Docsity!

CS 161 — Sorting and Searching

Algorithms

Table of Contents

  1. Searching Fundamentals
  2. Linear Search
  3. Binary Search
  4. InsertionSort
  5. MergeSort
  6. QuickSort
  7. Heapsort
  8. Selection Algorithms
  9. Comparison-Sort Lower Bound
  10. Algorithm Comparison
  11. Official CS 161 References

Searching Fundamentals

A search algorithm determines whether a target value appears in a collection and, often, returns its position.

The appropriate algorithm depends on whether the data is sorted:

Unsorted data: use linear search.  Sorted data: use binary search for fast lookup.

Searching is closely connected to sorting because sorting enables faster repeated searches.web.stanford+

Linear Search

Linear search scans an unsorted array from beginning to end.

text LINEAR-SEARCH(A, x): for i = 1 to n: if A[i] = x: return i

return NOT-FOUND

Running time

Case Running time Reason

Best case Θ(1)\Theta(1)Θ( 1 ) Target is the first element

Worst case Θ(n)\Theta(n)Θ(n) Target is last or absent

Average case Θ(n)\Theta(n)Θ(n) Expected position is about halfway through

Linear search is optimal for an unsorted array because, in the worst case, any correct algorithm must examine every element.

Binary Search

Binary search works only on a sorted array.

text BINARY-SEARCH(A, x): low = 1 high = n

while low <= high: mid = floor((low + high) / 2)

if A[mid] = x: return mid else if A[mid] < x: low = mid + 1 else: high = mid - 1

return NOT-FOUND

How it works

Each comparison eliminates half of the remaining search space:

n→n/2→n/4→⋯→1n \rightarrow n/2 \rightarrow n/4 \rightarrow \cdots \rightarrow 1n→n/2→n/4→⋯→ 1

Case Input Running time

Worst case Reverse sorted Θ(n2)\Theta(n^2)Θ(n2)

Average case Random order Θ(n2)\Theta(n^2)Θ(n2)

Stanford’s notes explain that a sorted input requires no shifts, while a reverse-sorted input requires approximately:

1+2+⋯+(n−1)=n(n−1)21 + 2 + \cdots + (n - 1) = \frac{n(n - 1)}{2}1+2+⋯+(n−1)=2n(n−1)

shifts, giving quadratic time.web.stanford+

Stability

InsertionSort is stable : equal elements retain their original relative order because the algorithm shifts only elements strictly greater than the key.web.stanford

MergeSort

MergeSort is a divide-and-conquer sorting algorithm.

text MERGE-SORT(A): if length(A) <= 1: return A

L = MERGE-SORT(left half of A) R = MERGE-SORT(right half of A)

return MERGE(L, R)

Merge step

To merge two sorted arrays, repeatedly compare their front elements and append the smaller one to the output.

Recurrence

MergeSort makes two recursive calls on arrays of size n/2n/2n/2, then merges them in Θ(n)\Theta(n)Θ(n) time:

T(n)=2T(n/2)+Θ(n)T(n) = 2T(n/2) + \Theta(n)T(n)=2T(n/2)+Θ(n)

By the Master Theorem:

T(n)=Θ(nlogn)T(n) = \Theta(n \log n)T(n)=Θ(nlogn)

Stanford’s CS 161 notes derive this recurrence and conclude that MergeSort has worst-case O(nlogn)O(n \log n)O(nlogn) time.stanford-cs161.github+

Stability

MergeSort is stable if the merge step, when encountering equal elements, takes the element from the left subarray first.

Space usage

Standard MergeSort requires Θ(n)\Theta(n)Θ(n) auxiliary space for merging.

QuickSort

QuickSort is another divide-and-conquer sorting algorithm, but it partitions around a pivot instead of merging sorted halves.stanford-cs161.github+

Algorithm

  1. Choose a pivot element xxx.
  2. Partition the array into: o AA_>A>: elements greater than xxx
  3. Recursively sort AA_>A>.
  4. Concatenate:

A<,x,A>A_< , x, A_>A<,x,A>

stanford-cs161.github+

Pseudocode

text QUICKSORT(A): if length(A) <= 1: return A

choose pivot x partition A into A<, x, A>

return QUICKSORT(A<) + [x] + QUICKSORT(A>)

in the worst case.

Building the heap takes Θ(n)\Theta(n)Θ(n), and each of the n−1n - 1n−1 extractions takes O(logn)O( \log n)O(logn).graphics.stanford+

Stability

Heapsort is not stable because heap operations can move equal elements far apart.

Selection Algorithms

The selection problem asks for the kkk-th smallest element in an unsorted array.

Simple approaches

Method Running time Idea

Sort, then index Θ(nlogn) \Theta(n \log n)Θ(nlogn) Sort and return the kkk-th element

Min-heap O(n+klogn)O(n + k^ \log n)O(n+klogn)

Build heap, extract minimum kkk times

Randomized QuickSelect Θ(n)\Theta(n)Θ(n) expected Partition and recurse into one side

Randomized QuickSelect

  1. Choose a random pivot.
  2. Partition the array around the pivot.
  3. If the pivot is the kkk-th smallest element, return it.
  4. Otherwise, recurse only into the side containing the desired rank.

Unlike QuickSort, QuickSelect recurses into only one subarray, giving expected linear time:

Θ(n)\Theta(n)Θ(n)

web.stanford+

Comparison-Sort Lower Bound

A comparison-based sort makes decisions only by comparing pairs of elements. Examples include InsertionSort, MergeSort, QuickSort, and Heapsort.web.stanford+

Decision-tree argument

There are n!n!n! possible orderings of nnn distinct elements.

A comparison-based sorting algorithm must distinguish all n!n!n! orderings. Its decision tree must therefore have at least n!n!n! leaves.

A binary tree with n!n!n! leaves has depth at least:

log2(n!) \log_2(n!)log2(n!)

Using Stirling’s approximation:

log2(n!)=Θ(nlogn) \log_2(n!) = \Theta(n \log n)log2(n!)=Θ(nlogn)

Therefore, every comparison-based sorting algorithm has worst-case running time:

Ω(nlogn) \Omega(n \log n)Ω(nlogn)

graphics.stanford+

Consequences

 MergeSort and Heapsort are asymptotically optimal comparison sorts.  QuickSort is not worst-case optimal, but is efficient in practice.  InsertionSort is asymptotically slower for large inputs.  Non-comparison sorts, such as counting sort or radix sort, can beat this bound under additional assumptions about the input.graphics.stanford+

Algorithm Comparison

Algorithm Best case Average/expected case Worst case Stable ? Extra space

Linear search

Θ(1)\Theta(1)Θ( 1 ) Θ(n)\Theta(n)Θ(n)^ Θ(n)\Theta(n)Θ(n)^ —^

Θ(1)\Theta(1)Θ( 1 )

Binary search

Θ(1)\Theta(1)Θ( 1 )

Θ(logn) \Theta(\lo g n)Θ(logn)

Θ(logn) \Theta(\lo g n)Θ(logn)

Θ(1)\Theta(1)Θ( 1 )

InsertionS ort

Θ(n)\Theta(n)Θ( n)

Θ(n2)\Theta(n^2)Θ (n2)

Θ(n2)\Theta(n^2)Θ (n2) Yes Θ(1)\Theta(1)Θ( 1 )

MergeSort

Θ(nlogn) \Thet a(n \log n)Θ(nlogn)

Θ(nlogn) \Theta(n \log n)Θ(nlogn)

Θ(nlogn) \Theta(n \log n)Θ(nlogn) Yes Θ(n)\Theta(n)Θ(n )