DSA – Arrays, Searching & Sorting

Array Basics

  • Ordered, fixed-size collection of same-type elements, contiguous in memory

  • Index range: 0n10 \rightarrow n-1 (direct access via subscript [][])

  • Size formula: N=U<em>bL</em>b+1N = U<em>b - L</em>b + 1

Core Array Operations

  • Traversal: visit each element once (read, print, process)

  • Insertion at position aa
    • If a=U<em>b+1a = U<em>b + 1 → append • Else shift right from U</em>baU</em>b \rightarrow a, place new item, update UbU_b

  • Deletion at position bb
    • Save A[b]A[b], shift left b+1U<em>bb+1 \rightarrow U<em>b, decrement U</em>bU</em>b

2-D & Multidimensional Arrays

  • Represented as rows & columns: A[i][j]A[i][j]

  • Memory layouts
    • Row-major: store rows consecutively
    • Column-major: store columns consecutively

  • Ragged arrays: rows of unequal length

Searching Algorithms

Linear (Sequential) Search
  • Scan from first to last element

  • Works on unsorted arrays

  • Complexity: best 11, worst NN, average N+12\tfrac{N+1}{2}O(N)O(N)

Binary Search
  • Requires sorted array

  • Repeatedly halve search range using middle element

  • Complexity: worst log2N\lceil\log_2 N\rceilO(logN)O(\log N)

Sorting Algorithms

Selection Sort
  • Repeatedly select smallest remaining element and swap into place

  • O(N2)O(N^2) comparisons, O(N)O(N) swaps

Bubble Sort
  • Repeatedly swap adjacent out-of-order pairs; large items “sink”

  • Worst O(N2)O(N^2) comparisons & swaps; best (already sorted) O(N)O(N)

Insertion Sort
  • Insert each element into its correct place within sorted prefix

  • Worst O(N2)O(N^2), best O(N)O(N) (nearly sorted)

Merge Sort (Divide & Conquer)
  • Recursively split array, sort halves, merge

  • Time O(NlogN)O(N \log N), extra space O(N)O(N)

Quick Sort (Divide, Partition, Conquer)
  • Partition around pivot into < pivot, = pivot, > pivot; recurse on subarrays

  • Average O(NlogN)O(N \log N); worst O(N2)O(N^2) (e.g., already sorted with bad pivot)

Radix Sort
  • Non-comparison sort; group items by each digit/character from least to most significant

  • Time O(dN)O(d\,N) for dd digits; high memory overhead, suited to linked lists

Complexity Comparison (Key Results)

  • Quadratic sorts (Selection, Bubble, Insertion): O(N2)O(N^2) worst-case; only viable for small NN or nearly sorted data

  • Efficient comparison sorts: Merge & Quick (avg) O(NlogN)O(N \log N), Heap sort (not detailed) also O(NlogN)O(N \log N)

  • Search: use Binary search on sorted data for O(logN)O(\log N) speed; otherwise Linear search O(N)O(N)