chapter

    Searching, Sorting, Selection and Hashing Notes for Gate Cs

    Searching, Sorting, Selection and Hashing notes for GATE CS: 38 study cards covering concepts, formulas, shortcuts and exam traps, plus solved practice questi

    Searching Sorting Selection and Hashing notes

    Chapter Roadmap: Searching, Sorting, Selection and Hashing

    Chapter Roadmap: Searching, Sorting, Selection and Hashing

    Your journey through this chapter:

    1. Sorting Algorithms and Operation Counts Master exact comparison and swap counts for Bubble, Insertion, Selection, Merge, and Quick sort.
    2. Binary and Bitonic Array Searching Achieve logarithmic time search in sorted and bitonic arrays.
    3. Selection and Comparison Bounds Learn the theoretical minimum comparisons required for selection problems.
    4. Linear-Time Array Property Verification Design single-pass algorithms to verify specific array conditions.
    5. Universal Hashing and Adversarial Inputs Choose hash functions that minimize collisions against malicious inputs.

    What you will master: Trace any sorting or searching algorithm, count its exact operations, and identify the most efficient approach for any data distribution.

    Sorting Algorithms and Operation Counts

    Sorting Algorithms and Operation Counts

    Why this matters: Sorting is not just about getting a sorted array; it is about understanding the computational cost of rearranging data. Different algorithms pay this cost in different ways: some through excessive comparisons, others through excessive data movement.

    What you will learn here:

    • How to derive exact comparison and swap counts for standard sorting algorithms.
    • The relationship between array inversions and sorting operation counts.
    • How to identify "void" operations in divide-and-conquer sorting.
    • Common pitfalls in analyzing loop bounds and operation totals.

    The core idea: An algorithm's efficiency on a specific input is determined by counting its fundamental operations. For sorting, these are comparisons (A[j] > A[j+1]) and data movements (swap or shift).

    Bubble Sort: Comparisons and Swaps

    Bubble Sort Operation Counts

    Standard Implementation:

    for i = 0 to n-2:
    for j = 0 to n-i-2:
    if A[j] > A[j+1]:
    swap(A[j], A[j+1])
    Comparisons:

    The inner loop executes times.
    Total comparisons = (Always, regardless of input).

    Swaps:

    A swap occurs if and only if there is an inversion (a pair of elements out of order).

    • Best case (already sorted): 0 swaps.
    • Worst case (reverse sorted): swaps.

    Key Insight: For bubble sort, the number of swaps is exactly equal to the number of inversions in the initial array.

    35 more cards in this chapter

    Try a question

    Answer it here to see how it works. Nothing is recorded until you sign in.

    Question 1
    Level 1: Warm-up

    In the randomized hashing strategy to defend against an adversary, the security guarantee relies on the chronological order of events. Let:

    E1: The adversary commits to a specific set of keys to insert.

    E2: The system randomly selects a hash function from a universal family .

    E3: The system inserts the keys using the selected .

    Which ordering of these events ensures that the adversary cannot force all keys into a single slot?

    Question 2
    Level 1: Warm-up

    A hash table has slots and uses a fixed, publicly known hash function . An adversary wants to insert distinct keys such that all of them collide in slot $0$. Which of the following conditions makes this attack impossible?

    Question 3
    Level 1: Warm-up

    Which of the following classic sorting algorithms performs exactly the same number of comparisons regardless of whether the input array is already sorted, reverse sorted, or randomly ordered?

    Question 4
    Level 1: Warm-up

    To verify the condition for an array of size , which of the following statements is TRUE?

    Question 5
    Level 1: Warm-up

    A global property of an array of size is defined as: "for every index from $1$ to , ". To verify this property for an arbitrary array of size , what is the worst-case time complexity of the optimal algorithm?

    Question 6
    Level 1: Warm-up

    An algorithm processes an array of size and performs exactly $99$ comparisons in the worst case to verify a global property. Which of the following properties could the algorithm be verifying?

    Question 7
    Level 1: Warm-up

    A hash table with slots uses a universal family of hash functions to store distinct keys. According to the definition of universal hashing, what is the maximum expected number of other keys that will collide with a specific key already in the table?

    Question 8
    Level 1: Warm-up

    Consider a hash table with slots using a universal family of hash functions to store distinct keys, where .

    Which of the following statements are TRUE about universal hashing?

    Question 9
    Level 1: Warm-up

    Consider a hash table using a universal family of hash functions to defend against adversarial inputs. Which of the following statements are TRUE?

    Question 10
    Level 1: Warm-up

    A hash table has slots and uses a universal family of hash functions. An adversary inserts distinct keys into the table. According to the properties of universal hashing, the expected number of other keys that collide with a specific key is bounded by . Compute this upper bound value.

    Free preview ends here

    Login to view the complete notes

    Creating an account is free. You get the rest of this chapter, step-by-step solutions, and a study plan built around the topics you are actually weak at.

    Explore complete test series, official past papers, and chapter-wise study tools.

    Why MastersUp

    Personalised first. High quality throughout.

    Most platforms hand everyone the same content. Here the content moves with your performance, topic by topic.

    Built around you, not around a syllabus PDF

    Every answer you give moves your topic-level intelligence rate. The next question, the next revision card and tomorrow's plan all change with it.

    Revision that hits your weak spots

    We only revise topics you have actually attempted and are still below the safe bar on — never the same chapter on repeat.

    Questions calibrated to the real exam

    Each question carries a measured toughness. You are served a rung above your current level, so practice keeps stretching you.

    Notes written for recall, not for volume

    Full lesson cards for first study, curated short-note cards for the last mile — with derivations, traps and exam patterns marked.

    One place for everything

    Notes, chapter practice, previous-year questions, test series and full-length papers — all feeding one picture of your preparation.

    Honest progress

    No vanity streaks. Progress here means chapters mastered and accuracy that held up on harder questions.

    Unlock the whole course

    Full notes and short notes, the complete question bank with worked solutions, mock tests, full-length papers, and an adaptive plan that rebuilds itself as you improve.

    Searching, Sorting, Selection and Hashing Notes for GATE CS

    Searching, Sorting, Selection and Hashing notes for GATE CS: 38 study cards covering concepts, formulas, shortcuts and exam traps, plus solved practice questions.

    Chapter Roadmap: Searching, Sorting, Selection and Hashing

    Chapter Roadmap: Searching, Sorting, Selection and Hashing

    Your journey through this chapter:

    1. Sorting Algorithms and Operation Counts Master exact comparison and swap counts for Bubble, Insertion, Selection, Merge, and Quick sort.
    2. Binary and Bitonic Array Searching Achieve logarithmic time search in sorted and bitonic arrays.
    3. Selection and Comparison Bounds Learn the theoretical minimum comparisons required for selection problems.
    4. Linear-Time Array Property Verification Design single-pass algorithms to verify specific array conditions.
    5. Universal Hashing and Adversarial Inputs Choose hash functions that minimize collisions against malicious inputs.

    What you will master: Trace any sorting or searching algorithm, count its exact operations, and identify the most efficient approach for any data distribution.

    Sorting Algorithms and Operation Counts

    Sorting Algorithms and Operation Counts

    Why this matters: Sorting is not just about getting a sorted array; it is about understanding the computational cost of rearranging data. Different algorithms pay this cost in different ways: some through excessive comparisons, others through excessive data movement.

    What you will learn here:

    • How to derive exact comparison and swap counts for standard sorting algorithms.
    • The relationship between array inversions and sorting operation counts.
    • How to identify "void" operations in divide-and-conquer sorting.
    • Common pitfalls in analyzing loop bounds and operation totals.

    The core idea: An algorithm's efficiency on a specific input is determined by counting its fundamental operations. For sorting, these are comparisons (A[j] > A[j+1]) and data movements (swap or shift).

    Bubble Sort: Comparisons and Swaps

    Bubble Sort Operation Counts

    Standard Implementation:

    for i = 0 to n-2:
    for j = 0 to n-i-2:
    if A[j] > A[j+1]:
    swap(A[j], A[j+1])
    Comparisons:

    The inner loop executes times.
    Total comparisons = (Always, regardless of input).

    Swaps:

    A swap occurs if and only if there is an inversion (a pair of elements out of order).

    • Best case (already sorted): 0 swaps.
    • Worst case (reverse sorted): swaps.

    Key Insight: For bubble sort, the number of swaps is exactly equal to the number of inversions in the initial array.

    Insertion Sort: The Power of Inversions

    Insertion Sort Operation Counts

    Mechanism: For each element, shift larger sorted elements to the right until the correct position is found.

    Operation Counts (tied to inversions ):

    • Comparisons:
    • Shifts (Data Movements):
    Best case (sorted):

    . Comparisons = , Shifts = $0$. Complexity: .

    Worst case (reverse sorted):

    . Comparisons and Shifts both . Complexity: .

    Key Insight: Insertion sort is highly adaptive. Its runtime is , making it exceptionally fast for nearly sorted arrays.

    Searching, Sorting, Selection and Hashing: Solved Questions with Step-by-Step Explanations (10 Problems)

    Question 1 · Algorithms MCQ

    In the randomized hashing strategy to defend against an adversary, the security guarantee relies on the chronological order of events. Let:

    E1: The adversary commits to a specific set of keys to insert.

    E2: The system randomly selects a hash function from a universal family .

    E3: The system inserts the keys using the selected .

    Which ordering of these events ensures that the adversary cannot force all keys into a single slot?

    1. A.

      E2 E1 E3

    2. B.

      E2 E3 E1

    3. C.

      E1 E2 E3

    4. D.

      E1 E3 E2

    Correct Answer:

    C

    Step-by-Step Solution

    Key idea: The core defense of universal hashing is that the adversary must commit to their keys <b>before</b> knowing which hash function is selected.

    Step 1: Analyze the requirement. For randomization to work, must be unknown to the adversary when they choose their keys.

    Step 2: Evaluate the order. The adversary must choose keys (E1) first. Then the system picks (E2). Finally, the system inserts (E3).

    Step 3: This corresponds to the sequence E1 E2 E3.

    Answer: The correct ordering is E1 E2 E3.

    Question 2 · Algorithms MCQ

    A hash table has slots and uses a fixed, publicly known hash function . An adversary wants to insert distinct keys such that all of them collide in slot $0$. Which of the following conditions makes this attack impossible?

    1. A.

      The adversary knows the value of .

    2. B.

      The universe of valid keys contains strictly fewer than elements.

    3. C.

      The table size is chosen to be a prime number.

    4. D.

      The number of keys is strictly greater than .

    Correct Answer:

    B

    Step-by-Step Solution

    Key idea: The adversary needs distinct keys from the universe . If , the adversary cannot even select keys, making the attack impossible by definition.

    Step 1: Analyze the attack. The adversary wants keys that all map to slot $0$. For , these keys must be multiples of .

    Step 2: Evaluate Option A. Knowing helps the adversary construct the keys. It does not prevent the attack.

    Step 3: Evaluate Option B. If the universe has fewer than elements, the adversary cannot choose distinct keys. The attack is impossible.

    Step 4: Evaluate Option C. Choosing as prime does not prevent the existence of multiples of in the universe.

    Step 5: Evaluate Option D. If , collisions are inevitable, but it doesn't prevent all keys from landing in the <i>same</i> slot.

    Answer: The universe of valid keys contains strictly fewer than elements.

    Question 3 · Algorithms MCQ

    Which of the following classic sorting algorithms performs exactly the same number of comparisons regardless of whether the input array is already sorted, reverse sorted, or randomly ordered?

    1. A.

      Insertion Sort

    2. B.

      Bubble Sort (with early termination flag)

    3. C.

      Selection Sort

    4. D.

      Quick Sort

    Correct Answer:

    C

    Step-by-Step Solution

    Key idea: This is a comparative operation count question, testing knowledge of which algorithms are "adaptive" versus "non-adaptive" in their comparison behavior.

    Step 1: Insertion Sort is adaptive; it makes comparisons on a sorted array but on a reverse sorted array.

    Step 2: Bubble Sort with an early termination flag is adaptive; it makes comparisons on a sorted array.

    Step 3: Quick Sort's comparison count heavily depends on pivot selection and the initial order of the array.

    Step 4: Selection Sort always scans the entire unsorted portion to find the minimum element, performing exactly comparisons in all cases.

    Answer: C

    Question 4 · Algorithms MCQ

    To verify the condition for an array of size , which of the following statements is TRUE?

    1. A.

      It requires comparisons because of the two universal quantifiers.

    2. B.

      It can be verified in time by checking if the sequence of adjacent differences is strictly increasing.

    3. C.

      It requires sorting the array first, taking time.

    4. D.

      It can only be verified in time if the array elements are distinct.

    Correct Answer:

    B

    Step-by-Step Solution

    Key idea: This is a translation question that reduces a complex global condition with quantifiers to a simple local monotonic property.

    Step 1: Analyze the condition. Let be the adjacent difference at index . The condition states that for any , .

    Step 2: Recognize the pattern. The statement "for any , " is the exact definition of a strictly increasing sequence.

    Step 3: Formulate the local check. Therefore, the global condition is equivalent to checking if for all valid .

    Step 4: Determine the complexity. This requires a single pass over the array to compute and compare adjacent differences, taking time.

    Answer: B

    Question 5 · Algorithms MCQ

    A global property of an array of size is defined as: "for every index from $1$ to , ". To verify this property for an arbitrary array of size , what is the worst-case time complexity of the optimal algorithm?

    1. A.

    2. B.

    3. C.

    4. D.

    Correct Answer:

    C

    Step-by-Step Solution

    Key idea: The condition "for every index from $1$ to " describes a relationship between adjacent elements. This is a transitive property, meaning if it holds for all adjacent pairs, it holds globally.

    Step 1: Recognize that verifying requires exactly one comparison per adjacent pair.

    Step 2: Count the number of adjacent pairs in an array of size . There are exactly such pairs.

    Step 3: Since we perform exactly comparisons in a single pass, the time complexity is strictly proportional to .

    Answer: The worst-case time complexity is .

    Question 6 · Algorithms MCQ

    An algorithm processes an array of size and performs exactly $99$ comparisons in the worst case to verify a global property. Which of the following properties could the algorithm be verifying?

    1. A.

      The array contains no duplicate elements.

    2. B.

      The array is sorted in non-decreasing order.

    3. C.

      The array is a permutation of integers from $1$ to $N$.

    4. D.

      All elements in the array are strictly positive.

    Correct Answer:

    B

    Step-by-Step Solution

    Key idea: Reverse engineer the property from the operation count. $99$ comparisons for $N=100$ means exactly $N-1$ comparisons, which is the signature of checking adjacent elements in a single pass.

    Step 1: Analyze the operation count. $99 = 100 - 1 = N - 1$. This implies the algorithm checks exactly $N-1$ pairs.

    Step 2: Evaluate Option A. Checking for duplicates in an arbitrary array requires $O(N^2)$ comparisons or $O(N \log N)$ if sorted first. It does not take exactly $N-1$ comparisons.

    Step 3: Evaluate Option B. Checking if an array is sorted requires comparing each element with its successor. There are $N-1$ such pairs, so it takes exactly $N-1$ comparisons. This matches.

    Step 4: Evaluate Option C. Verifying a permutation requires checking both the range and uniqueness, which takes more than $N-1$ comparisons.

    Step 5: Evaluate Option D. Checking if all elements are positive requires checking each of the $N$ elements, taking $N$ comparisons, not $N-1$.

    Answer: The array is sorted in non-decreasing order.

    Question 7 · Algorithms MCQ

    A hash table with slots uses a universal family of hash functions to store distinct keys. According to the definition of universal hashing, what is the maximum expected number of other keys that will collide with a specific key already in the table?

    1. A.

      5.01

    2. B.

      5.00

    3. C.

      4.99

    4. D.

      10.00

    Correct Answer:

    B

    Step-by-Step Solution

    Key idea: This is a direct formula application question. The universal hashing property bounds the expected number of collisions for a specific key with the other keys.

    Step 1: Identify the number of other keys in the table. Since there are keys in total, the number of other keys is .

    Step 2: Apply the universal hashing collision bound formula. The expected number of collisions for a specific key is at most .

    Step 3: Substitute the values into the formula: .

    Answer: The maximum expected number of other keys that will collide with is 5.00.

    Question 8 · Algorithms MSQ

    Consider a hash table with slots using a universal family of hash functions to store distinct keys, where .

    Which of the following statements are TRUE about universal hashing?

    1. A.

      For any two distinct keys and , r[h(x) = h(y)] \leq rac{1}{m}

    2. B.

      The expected number of keys colliding with a specific key is at most

    3. C.

      The hash function is chosen randomly at runtime from the family

    4. D.

      Universal hashing guarantees zero collisions for any input

    Correct Answer:

    ["A","B","C"]

    Step-by-Step Solution

    Key idea: This is a "universal hashing properties" question. Recall the definition and implications.

    Step 1: Evaluate option A

    • Definition of universal family: for
    • This is the fundamental property
    • Option A is TRUE

    Step 2: Evaluate option B

    • For a specific key , expected collisions =
    • Option B is TRUE

    Step 3: Evaluate option C

    • Universal hashing defends against adversaries by randomizing the hash function
    • The function is chosen uniformly at random from family at runtime
    • Option C is TRUE

    Step 4: Evaluate option D

    • Universal hashing does NOT eliminate collisions
    • It ensures collisions are rare and unpredictable
    • Collisions still occur due to randomness
    • Option D is FALSE

    Answer: A, B, C are true

    Question 9 · Algorithms MSQ

    Consider a hash table using a universal family of hash functions to defend against adversarial inputs. Which of the following statements are TRUE?

    1. A.

      For any two distinct keys and , the probability of collision .

    2. B.

      The hash function is chosen uniformly at random from at runtime.

    3. C.

      Universal hashing guarantees that absolutely zero collisions will occur for any input.

    4. D.

      The adversary must commit to their set of keys before knowing which specific was selected.

    Correct Answer:

    ["A","B","D"]

    Step-by-Step Solution

    Key idea: This is a "universal hashing properties" question. Evaluate each statement against the definition and threat model.

    Step 1: Evaluate Option A (Collision probability)

    • This is the exact mathematical definition of a universal hash family.
    • for .
    • Option A is TRUE.

    Step 2: Evaluate Option B (Randomization)

    • The defense mechanism relies on picking randomly from at runtime.
    • This prevents the adversary from predicting the hash values.
    • Option B is TRUE.

    Step 3: Evaluate Option C (Zero collisions)

    • Universal hashing minimizes the PROBABILITY of collisions, but does not eliminate them.
    • Collisions still occur due to randomness; they are just bounded in expectation.
    • Option C is FALSE.

    Step 4: Evaluate Option D (Adversary model)

    • The security guarantee assumes the adversary chooses keys BEFORE is selected.
    • If they could see first, they could easily craft collisions.
    • Option D is TRUE.

    Answer: A, B, D

    Question 10 · Algorithms NAT

    A hash table has slots and uses a universal family of hash functions. An adversary inserts distinct keys into the table. According to the properties of universal hashing, the expected number of other keys that collide with a specific key is bounded by . Compute this upper bound value.

    Correct Answer:

    5.00

    Step-by-Step Solution

    Key idea: This is a "universal hashing expected collisions" question. Apply the expectation bound formula directly.

    Step 1: Recall the formula

    • For a specific key , the expected number of other keys colliding with it is .

    Step 2: Substitute the given values

    • (total keys).
    • (number of slots).
    • Bound = .

    Step 3: Compute the value

    • Bound = .

    Answer: 5.00

    More notes in this unit