IAE Academy

GATE CS · DA

Searching, sorting and hashing

Searching, sorting and hashing cover how to find, order and index data. The topic includes linear and binary search (with exact comparison counts) and the elementary sorts (bubble, selection, insertion). It then covers the efficient comparison sorts (merge, quick, heap), which cannot beat the Omega(n log n) lower bound, and the non-comparison sorts (counting, radix), which beat it when keys are small integers. Finally it covers hash tables (chaining, linear and quadratic probing, double hashing) with their load-factor-dependent probe counts. Most questions come down to tracing an algorithm by hand under a stated convention, or plugging values into one of a small set of standard results. Both are drilled here.

18 previous-year questions · 18 solved · 5 practice questions

1. Linear search and binary search

Searching means locating a key in a collection of elements. Linear search scans one element at a time and needs no ordering. Binary search repeatedly halves the search space. It requires the array to be sorted and O(1) random access to any index. Applied to an unsorted array it can miss a key that is present, and on a linked list reaching the middle alone costs .

Linear search procedure

  1. Start at index 0.

  2. Compare the current element with the key.

  3. If equal, return the index (success).

  4. Otherwise move to the next index.

  5. If the end of the array is reached with no match, report failure.

LINEAR SEARCH: NUMBER OF KEY COMPARISONS

The successful-search average assumes the key is present and equally likely to be at each of the positions. Both the worst case and the average case are .

Binary search procedure (array sorted ascending, 0-indexed, `low = 0`, `high = n - 1`)

  1. While low <= high, compute mid = low + (high - low) / 2 (integer division). This equals (low + high) / 2 whenever that sum does not overflow int; the first form simply avoids the overflow for very large indices.

  2. If a[mid] == key, return mid.

  3. If a[mid] < key, set low = mid + 1 (search the right half).

  4. If a[mid] > key, set high = mid - 1 (search the left half).

  5. If the loop ends with low > high, report failure.

BINARY SEARCH COMPLEXITY

Convention: each probe of a[mid] counts as one (three-way) comparison. The worst case holds for both successful and unsuccessful search. If a question counts the == test and the < test as separate comparisons, recount under its rule. Valid only for a sorted array with random access.

WORKED EXAMPLE · TRACE

Array (sorted, 0-indexed): [2, 5, 8, 12, 16, 23, 38, 45, 56, 72, 91], so . Using the procedure above, how many probes does binary search make to find key = 72? Which key needs the worst-case number of probes, and how many is that?

Solution
  1. Key 72. Probe 1: low = 0, high = 10, mid = 5, a[5] = 23 < 72, so low = 6.

  2. Probe 2: low = 6, high = 10, mid = 6 + 4/2 = 8, a[8] = 56 < 72, so low = 9.

  3. Probe 3: low = 9, high = 10, mid = 9 + 1/2 = 9, a[9] = 72: found at index 9 after 3 probes.

  4. Key 91 follows the same path to low = 9. Probe 3 gives a[9] = 72 < 91, so low = 10. Probe 4: mid = 10, a[10] = 91, found. That is 4 probes.

  5. Check: , so no key (and no unsuccessful search) needs more than 4 probes.

Answer: Key 72 is found at index 9 in 3 probes. Key 91 needs the worst case of 4 probes, which matches .

FINDING THE MINIMUM AND MAXIMUM TOGETHER

Method: take the elements in pairs. Compare the two elements of each pair with each other, then the smaller with the current minimum and the larger with the current maximum. That is 3 comparisons per pair instead of 4. Finding only the maximum (or only the minimum) takes exactly comparisons. Both counts are the best possible for comparison-based algorithms.

EXAM TIP

When a question asks for the worst-case number of comparisons for a specific (e.g. gives ), use directly, after checking how the question counts a comparison. Also check that the array is actually sorted before applying binary search.

2. Sorting fundamentals: stability, in-place, and the comparison lower bound

Convention for this whole topic unless a question says otherwise: complexities are worst case, logarithms are base 2, and programs are C with 0-indexed arrays and 4-byte int. A sort is stable if two elements with equal keys keep their original relative order in the output. A sort is in-place if it uses only extra storage outside the input array. The recursion stack is reported separately, which is why quicksort is called in-place even though its stack uses space on average. If a question gives its own definition of in-place, use that.

Core vocabulary

Term

Meaning

Why it matters

Comparisons

Number of times two keys are compared

Determines the lower bound for comparison-based sorts

Swaps / moves

Number of times elements exchange or shift positions

Determines data-movement cost, relevant for large records

Pass

One sweep over the (remaining) array

Used to count iterations in bubble and selection sort

Inversion

A pair with but

Equals the swap count of bubble sort and the shift count of insertion sort

Stable

Equal keys keep their original relative order

Matters when records are sorted by one field but carry other data

In-place

extra storage outside the input (recursion stack reported separately)

Matters for memory-constrained sorting

LOWER BOUND FOR COMPARISON-BASED SORTING

Any sort that learns about the keys only by comparing pairs of them must make comparisons in the worst case, and also on average. Proof idea: there are possible orderings of distinct keys. A binary decision tree that distinguishes them all has at least leaves, so its height is at least , and by Stirling's approximation.

EXAM TIP

This lower bound applies only to comparison-based sorts. Counting sort and radix sort beat it because they use the key values directly, as array indices or extracted digits, instead of comparing pairs. This is not a contradiction: it is exactly why they are called non-comparison sorts, and why they need extra conditions on the keys.

3. Elementary O(n^2) sorts: bubble, selection, insertion

All three are quadratic in the worst case. They differ in how their cost depends on the input, whether they are stable, and how many swaps they make compared with comparisons. Questions often probe exactly these differences rather than just the complexity class.

Bubble, selection and insertion sort compared (n elements; standard versions: bubble sort compares $n-i$ adjacent pairs in pass $i$)

Algorithm

Comparisons (worst)

Swaps / shifts (worst)

Passes

Stable

In-place

Best case

Bubble sort

swaps (reverse-sorted input); in general, swaps = number of inversions

(fewer with an early-exit flag)

Yes

Yes

only with an early-exit flag: one pass of comparisons on sorted input

Selection sort

on every input

At most swaps (one per pass)

No (swap version)

Yes

: the comparison count does not depend on input order

Insertion sort

shifts; in general, shifts = number of inversions

Yes

Yes

: comparisons and 0 shifts on sorted input

NUMBER OF INVERSIONS

The maximum occurs for reverse-sorted input. The expected value is for a uniformly random permutation of distinct keys, since each of the pairs is inverted with probability . Insertion sort runs in time, so it is fast on nearly sorted input.

Selection sort's defining property is that its comparison count is input-independent. It always scans the whole unsorted part to find the minimum, so its best-case and worst-case comparison counts are both . Bubble sort (with an early-exit flag) and insertion sort, by contrast, finish in linear time on already-sorted data.

Insertion sort procedure (0-indexed, in place, ascending)

  1. For i = 1 to n - 1, let key = a[i].

  2. Set j = i - 1.

  3. While j >= 0 and a[j] > key: shift a[j] to a[j + 1] and decrement j.

  4. Place key at a[j + 1].

  5. After each iteration the prefix a[0..i] is sorted. The strict > is what makes the sort stable.

The C version below follows the convention stated in Section 2.

void insertionSort(int a[], int n) {
    for (int i = 1; i < n; i++) {
        int key = a[i];
        int j = i - 1;
        while (j >= 0 && a[j] > key) {
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;
    }
}

WORKED EXAMPLE · BUBBLE SORT TRACE

Sort [4, 2, 5, 1] ascending with standard bubble sort: in pass (), compare the adjacent pairs at positions and swap if left > right. How many comparisons and swaps are made in total?

Solution
  1. Pass 1 (3 comparisons): (4,2) swap → [2,4,5,1]; (4,5) no swap; (5,1) swap → [2,4,1,5]. 2 swaps; 5 is now in its final place.

  2. Pass 2 (2 comparisons): (2,4) no swap; (4,1) swap → [2,1,4,5]. 1 swap.

  3. Pass 3 (1 comparison): (2,1) swap → [1,2,4,5]. 1 swap.

  4. Totals: comparisons and swaps.

  5. Check the swaps against the inversions of [4,2,5,1]: (4,2), (4,1), (2,1), (5,1). That is 4 inversions, matching the swap count.

  6. An early-exit flag saves nothing here, because pass 3 still performs a swap and passes is the maximum anyway.

Answer: 6 comparisons and 4 swaps. The number of swaps always equals the number of inversions.

EXAM TIP

The standard swap-based selection sort is not stable. For example, sorting swaps 1 with and gives . A variant that inserts the minimum at position by shifting the intervening elements right, instead of swapping, is stable. Read the implementation a question describes before answering.

4. Efficient comparison sorts: merge sort, quicksort, heap sort

These three achieve at least on average, using divide-and-conquer or a heap. Merge sort and heap sort achieve it in the worst case as well.

BALANCED DIVIDE-AND-CONQUER RECURRENCE (MERGE SORT)

This applies whenever a problem of size is split into 2 equal halves with linear combine cost. The recursion tree has levels, each costing in total.

QUICKSORT RECURRENCES

Even a lopsided but constant-fraction split, such as 1 : 9, gives . Only a split that leaves a constant number of elements on one side at every level gives .

Merge sort, quicksort and heap sort compared

Algorithm

Best

Average

Worst

Extra space

Stable

In-place

Merge sort

auxiliary array

Yes

No (standard array version)

Quicksort

Recursion stack: average, worst with naive recursion

No

Yes

Heap sort

No

Yes

COMPARISONS TO MERGE TWO SORTED LISTS

This is for the standard two-pointer merge of sorted lists of sizes and . The worst case occurs when the lists interleave. The best case occurs when every element of the shorter list is smaller than every element of the longer one.

Quicksort: Lomuto partition procedure (pivot = last element)

  1. Choose pivot = a[high].

  2. Set i = low - 1, the boundary of the elements known to be <= pivot.

  3. For j = low to high - 1: if a[j] <= pivot, increment i and swap a[i] with a[j].

  4. After the loop, swap a[i + 1] with a[high]. The pivot is now in its final sorted position i + 1.

  5. Recursively sort the left part low .. i and the right part i + 2 .. high.

int partition(int a[], int low, int high) {
    int pivot = a[high];
    int i = low - 1;
    for (int j = low; j < high; j++) {
        if (a[j] <= pivot) {
            i++;
            int t = a[i]; a[i] = a[j]; a[j] = t;
        }
    }
    int t = a[i + 1]; a[i + 1] = a[high]; a[high] = t;
    return i + 1;
}

void quicksort(int a[], int low, int high) {
    if (low < high) {
        int p = partition(a, low, high);
        quicksort(a, low, p - 1);
        quicksort(a, p + 1, high);
    }
}

EXAM TIP

Quicksort's worst case occurs on already-sorted or reverse-sorted input when the pivot is always the first or last element. Every partition is then maximally unbalanced (0 and elements). With Lomuto partitioning it also occurs when all keys are equal, because every element satisfies a[j] <= pivot. A uniformly random pivot gives an expected time on every input, but its worst case is still . Median-of-three removes the sorted-input worst case but gives no worst-case guarantee.

BINARY HEAP OPERATION COSTS (HEAP OF N ELEMENTS)

Bottom-up build-heap is , not , because most nodes sit near the bottom and sift down only a short distance. Heap sort is build-heap followed by extract-max operations: .

EXAM TIP

Of these three, heap sort is the only one that is both in the worst case and uses extra space. It is not stable. Merge sort is the stable one of the three, at the cost of extra space.

5. Linear-time sorts: counting sort and radix sort

When the keys are integers in a known bounded range, sorting can beat the comparison lower bound. The trick is not to compare keys at all but to use them as array indices.

COUNTING SORT COMPLEXITY

= number of elements; the keys are integers in . The sort is linear when and degrades when is much larger than . It is stable when the output is filled by scanning the input from right to left, as below. It is not in-place.

RADIX SORT COMPLEXITY

= number of digits (passes) and = the range of one digit ( for decimal digits, for bits). Least-significant-digit radix sort applies a stable sort, usually counting sort, once per digit. The total is linear when is a constant and . It is not in-place.

Counting sort procedure (keys in the range 0..k-1)

  1. Create a count array C of size k, initialised to 0.

  2. For each input element, increment C[value].

  3. Turn C into prefix sums: C[i] += C[i - 1] for i = 1 to k - 1. Now C[i] is the number of elements <= i.

  4. Scan the input from the last element to the first (this order is what makes the sort stable). Place each element at output position C[value] - 1, then decrement C[value].

  5. The output array is sorted, and equal keys keep their relative input order.

WORKED EXAMPLE · COUNTING SORT TRACE

Sort [4, 1, 3, 1, 4] using counting sort (keys in the range 0 to 4, so ).

Solution
  1. Count array C (index 0..4): [0, 2, 0, 1, 2], i.e. two 1s, one 3 and two 4s.

  2. Prefix sums: C = [0, 2, 2, 3, 5].

  3. Input index 4 (value 4) goes to output[C[4] - 1] = output[4], and C[4] becomes 4.

  4. Input index 3 (value 1) goes to output[C[1] - 1] = output[1], and C[1] becomes 1.

  5. Input index 2 (value 3) goes to output[C[3] - 1] = output[2], and C[3] becomes 2.

  6. Input index 1 (value 1) goes to output[C[1] - 1] = output[0], and C[1] becomes 0.

  7. Input index 0 (value 4) goes to output[C[4] - 1] = output[3], and C[4] becomes 3.

  8. Output: [1, 1, 3, 4, 4].

Answer: [1, 1, 3, 4, 4]. The 1 from input index 1 lands before the 1 from index 3, and the 4 from index 0 lands before the 4 from index 4, so the sort is stable.

EXAM TIP

Radix sort's correctness depends on the per-digit sort being stable. Sorting from the least significant digit to the most significant works only if elements with equal current digits keep the order the previous passes gave them. With an unstable per-digit sort the final output can be wrong.

6. Hashing: hash functions, chaining, open addressing, load factor

A hash table maps keys to array slots through a hash function . When collisions are handled well, it gives expected search, insert and delete. Questions on this topic typically ask (a) where a key lands under a given collision-resolution scheme, and (b) the expected number of probes under each scheme.

Common hash functions

  1. Division method: . It is simple. is best chosen as a prime not close to a power of 2, so the result depends on all the bits of , not only the low-order ones.

  2. Multiplication method: for a constant . It is less sensitive to the choice of .

LOAD FACTOR

= number of keys stored, = number of slots. With chaining, can exceed 1. With open addressing every key needs its own slot, so . The open-addressing formulas below need , i.e. at least one free slot.

EXPECTED PROBES: SEPARATE CHAINING (SIMPLE UNIFORM HASHING, NEW KEYS INSERTED AT THE HEAD OF THEIR CHAIN)

These count the keys examined. An unsuccessful search walks the whole chain, whose expected length is . A successful search examines the target plus the keys inserted into the same chain after it. Including the hash computation, both searches take time. In the worst case, when all keys hash to one slot, a search takes .

EXPECTED PROBES: OPEN ADDRESSING UNDER UNIFORM HASHING (EVERY PROBE SEQUENCE EQUALLY LIKELY)

These are upper bounds, valid for . Uniform hashing is an idealisation that double hashing approximates well. Linear and quadratic probing do worse because of clustering.

EXPECTED PROBES: LINEAR PROBING (APPROXIMATIONS FOR LARGE TABLES)

Valid for . The squared term in the unsuccessful case shows how quickly primary clustering hurts as the table fills up.

Chaining vs open-addressing variants ($i = 0, 1, 2, \dots$ is the probe number)

Scheme

Probe sequence

Clustering

Can n exceed m?

Deletion

Separate chaining

One linked list (or other structure) per slot

None (no probing)

Yes, can exceed 1

Simple: remove from the list

Linear probing

Primary clustering: runs of occupied slots grow and merge

No

Needs a 'deleted' marker (tombstone), not 'empty'

Quadratic probing

Secondary clustering: keys with the same start slot follow the same probe sequence

No

Same tombstone caveat

Double hashing

Least clustering of the three; closest to uniform hashing

No

Same tombstone caveat

When the probe sequence reaches every slot

  1. Linear probing always visits all slots.

  2. Double hashing visits all slots exactly when is relatively prime to for every key. Two standard ways to guarantee this: make prime and , or make a power of 2 and always odd. If , the sequence never leaves the first slot.

  3. Quadratic probing need not visit every slot, so an insert can fail even when free slots exist. With , prime and , an empty slot is always found.

WORKED EXAMPLE · QUADRATIC PROBING TRACE

Table size , , quadratic probing with and , so . Insert keys 15, 8, 1 and 22 in this order into an empty table. Where does 22 land?

Solution
  1. . Slot 1 is empty, so 15 goes to slot 1.

  2. . Slot 1 is occupied; gives , which is empty, so 8 goes to slot 2.

  3. . Slot 1 is occupied; gives slot 2 (occupied); gives , which is empty, so 1 goes to slot 5.

  4. . Slot 1 is occupied; gives slot 2 (occupied); gives slot 5 (occupied); gives , which is empty, so 22 goes to slot 3.

Answer: Key 22 is stored in slot 3, after 3 collisions (slots 1, 2 and 5).

EXAM TIP

In open addressing, never mark a deleted slot as simply 'empty'. A later search for a key that was placed beyond that slot during a collision would stop at the 'empty' slot and wrongly report failure. Use a distinct 'deleted' (tombstone) marker instead: searches probe past it, and inserts may reuse it.

PREVIOUS-YEAR QUESTIONS

18 questions from the CS and DA papers

Try each question first, then open the answer. We placed each question under a topic ourselves; the exam paper does not label topics.

See these papers in full: GATE CSE 2026 Set 1 · GATE CSE 2026 Set 2 · GATE CSE 2025 Set 1 · GATE CSE 2025 Set 2 · GATE CSE 2023 · GATE CSE 2022 · GATE CSE 2020 · GATE DA 2026 · GATE DA 2025 · GATE DA 2024

GATE 2026 CS1 Q.24

GATE 2026 · CS1Q.24 · 1 mark · MSQ

Consider a hash table that is initially empty. The hash table is maintained using open addressing with linear probing. The hash function used is .

Consider the following sequence of insertions performed on :

Which of the following positions in the hash table is/are empty after these insertions are performed?

  1. (A)

    0

  2. (B)

    10

  3. (C)

    2

  4. (D)

    1

Answer and solution
See the question in the paper
GATE 2026 CS1 Q.24: answer and solution

GATE 2026 CS2 Q.32

GATE 2026 · CS2Q.32 · 1 mark · NAT

Consider an array . Suppose the merge sort algorithm is executed on array to sort it in increasing order. The merge sort algorithm will carry out a total of 7 merge operations.

A merge operation on sorted left array and sorted right array is said to be void if the output of the merge operation is the elements of array followed by the elements of array .

The number of void merge operations among these 7 merge operations is __________. (answer in integer)

Answer and solution
See the question in the paper
GATE 2026 CS2 Q.32: answer and solution

GATE 2026 DA Q.31

GATE 2026 · DAQ.31 · 1 mark · NAT

Let A be a sorted array containing 1000 distinct integers. You perform a recursive binary search on A to find an element y. Suppose each comparison checks whether the middle element computed during the current recursive step is equal to, less than, or greater than y.

The maximum number of comparisons that may have to be performed if y is not an element of A is _______ . (Answer in integer)

Answer and solution
See the question in the paper
GATE 2026 DA Q.31: answer and solution

GATE 2026 DA Q.49

GATE 2026 · DAQ.49 · 2 marks · MSQ

Consider the problem of sorting the given array in ascending order:

P = [1, 2, 3, 5, 4]

Consider two sorting algorithms Bubble Sort (BS) and Insertion Sort (IS).

Let N1 be the total number of comparisons done by BS on the elements of P and N2 be the total number of comparisons done by IS on the elements of P.

Which of the following options is/are correct?

  1. (A)

    N1 = 10, N2 = 4

  2. (B)

    N1 > N2

  3. (C)

    IS on P will perform only one swap

  4. (D)

    Both BS and IS on P will make at least one unnecessary comparison (i.e., comparing elements that are already in correct order)

Answer and solution
See the question in the paper
GATE 2026 DA Q.49: answer and solution

GATE 2025 CS1 Q.33

GATE 2025 · CS1Q.33 · 1 mark · NAT

The pseudocode of a function fun() is given below:

fun(int A[0,...,n-1]){
    for i=0 to n-2
        for j=0 to n-i-2
            if (A[j]>A[j+1])
                then swap A[j] and A[j+1]
}

Let be an array storing 30 distinct integers in descending order. The number of swap operations that will be performed, if the function fun() is called with as argument, is __________. (Answer in integer)

Answer and solution
See the question in the paper
GATE 2025 CS1 Q.33: answer and solution

GATE 2025 CS1 Q.65

GATE 2025 · CS1Q.65 · 2 marks · NAT

In a double hashing scheme, and are the auxiliary hash functions. The size of the hash table is 11. The hash function for the -th probe in the open address table is . The following keys are inserted in the given order: 63, 50, 25, 79, 67, 24.

The slot at which key 24 gets stored is ________. (Answer in integer)

Answer and solution
See the question in the paper
GATE 2025 CS1 Q.65: answer and solution

GATE 2025 CS2 Q.41

GATE 2025 · CS2Q.41 · 2 marks · MCQ

An array of length with distinct elements is said to be bitonic if there is an index such that is sorted in the non-decreasing order and is sorted in the non-increasing order.

Which ONE of the following represents the best possible asymptotic bound for the worst-case number of comparisons by an algorithm that searches for an element in a bitonic array ?

  1. (A)

  2. (B)

  3. (C)

  4. (D)

Answer and solution
See the question in the paper
GATE 2025 CS2 Q.41: answer and solution

GATE 2025 DA Q.18

GATE 2025 · DAQ.18 · 1 mark · MCQ

Consider a hash table of size 10 with indices , with the hash function

where linear probing is used to handle collisions. The hash table is initially empty and then the following sequence of keys is inserted into the hash table: . The indices where the keys 14 and 15 are stored are, respectively

  1. (A)

    2 and 5

  2. (B)

    2 and 6

  3. (C)

    4 and 5

  4. (D)

    4 and 6

Answer and solution
See the question in the paper
GATE 2025 DA Q.18: answer and solution

GATE 2024 DA Q.21

GATE 2024 · DAQ.21 · 1 mark · MCQ

Consider performing uniform hashing on an open address hash table with load factor , where elements are stored in the table with slots. The expected number of probes in an unsuccessful search is at most .

Inserting an element in this hash table requires at most ______ probes, on average.

  1. (A)

  2. (B)

  3. (C)

  4. (D)

Answer and solution
See the question in the paper
GATE 2024 DA Q.21: answer and solution

GATE 2024 DA Q.45

GATE 2024 · DAQ.45 · 2 marks · MCQ

Consider the following sorting algorithms:

(i) Bubble sort
(ii) Insertion sort
(iii) Selection sort

Which ONE among the following choices of sorting algorithms sorts the numbers in the array [4, 3, 2, 1, 5] in increasing order after exactly two passes over the array?

  1. (A)

    (i) only

  2. (B)

    (iii) only

  3. (C)

    (i) and (iii) only

  4. (D)

    (ii) and (iii) only

Answer and solution
See the question in the paper
GATE 2024 DA Q.45: answer and solution

GATE 2023 CS Q.20

GATE 2023 · CSQ.20 · 1 mark · MCQ

An algorithm has to store several keys generated by an adversary in a hash table. The adversary is malicious who tries to maximize the number of collisions. Let be the number of keys, be the number of slots in the hash table, and .

Which one of the following is the best hashing strategy to counteract the adversary?

  1. (A)

    Division method, i.e., use the hash function .

  2. (B)

    Multiplication method, i.e., use the hash function , where is a carefully chosen constant.

  3. (C)

    Universal hashing method.

  4. (D)

    If is a prime number, use Division method. Otherwise, use Multiplication method.

Answer and solution
See the question in the paper
GATE 2023 CS Q.20: answer and solution

GATE 2020 CS Q.23

GATE 2020 · CSQ.23 · 1 mark · NAT

Consider a double hashing scheme in which the primary hash function is , and the secondary hash function is . Assume that the table size is 23. Then the address returned by probe 1 in the probe sequence (assume that the probe sequence begins at probe 0) for key value is ____.

Answer and solution
See the question in the paper
GATE 2020 CS Q.23: answer and solution

PRACTICE

5 questions to test yourself

PRACTICE 11 mark · MCQ

An array of distinct elements is sorted using quicksort that always chooses the first element of the current subarray as pivot. If the input array is already sorted in increasing order, what is the running time of this run?

  1. (A)

  2. (B)

  3. (C)

  4. (D)

Answer and solution

Answer: (C)

  1. On a sorted subarray, the first element is the smallest, so the partition puts 0 elements on its left and all the other elements on its right.

  2. Each call therefore removes only the pivot, giving . The is the partition's pass over the subarray.

  3. The partition comparisons total , so .

  4. This is quicksort's worst case: a fixed first- or last-element pivot on sorted (or reverse-sorted) input degrades it from its average to .

PRACTICE 22 marks · NAT

The standard insertion sort (for i = 1 to n - 1: key = a[i]; while j >= 0 and a[j] > key, execute a[j + 1] = a[j] and decrement j; then a[j + 1] = key) is run on the array to sort it in ascending order. How many times is the shift a[j + 1] = a[j] executed in total?

Answer and solution

Answer:

  1. Each shift moves one larger element past the key, which removes exactly one inversion, i.e. a pair with . So the total number of shifts equals the number of inversions.

  2. The inversions of are (5,3), (5,4), (5,1), (5,2), (3,1), (3,2), (4,1) and (4,2). (3,4) and (1,2) are not inversions. That is 8 of the pairs.

  3. Direct trace. Insert 3: 5 shifts right, giving [3,5,4,1,2], 1 shift. Insert 4: 5 shifts right, giving [3,4,5,1,2], 1 shift. Insert 1: 5, 4 and 3 shift right, giving [1,3,4,5,2], 3 shifts. Insert 2: 5, 4 and 3 shift right, giving [1,2,3,4,5], 3 shifts.

  4. Total , which agrees with the inversion count.

PRACTICE 31 mark · MSQ

Which of the following sorting algorithms, in their standard textbook implementation, are stable (equal keys keep their original relative order)?

  1. (A)

    Bubble sort (adjacent-swap version, swapping only when left > right)

  2. (B)

    Selection sort (find the minimum and swap it into place)

  3. (C)

    Insertion sort (shifting while the element is strictly greater than the key)

  4. (D)

    In-place quicksort (Lomuto partition)

Answer and solution

Answer: (A), (C)

  1. Bubble sort swaps adjacent elements only when the left one is strictly greater, so two equal elements are never swapped past each other: stable.

  2. Insertion sort shifts an element right only while it is strictly greater than the key, so the key never moves in front of an equal element: stable.

  3. Selection sort's swap can carry an element over an equal one lying between the two swapped positions. For example, becomes : not stable.

  4. Quicksort with Lomuto (or Hoare) partitioning swaps elements over long distances, which can reorder equal keys: not stable.

  5. The stable ones are A and C.

PRACTICE 42 marks · MCQ

A hash table of size uses with linear probing . Keys 22, 44, 33 and 55 are inserted in this order into an initially empty table. At which index is key 55 finally stored?

  1. (A)

    Index 0

  2. (B)

    Index 1

  3. (C)

    Index 2

  4. (D)

    Index 3

Answer and solution

Answer: (D)

  1. . Slot 0 is empty, so 22 goes to index 0.

  2. . Slot 0 is occupied; slot 1 is empty, so 44 goes to index 1.

  3. . Slots 0 and 1 are occupied; slot 2 is empty, so 33 goes to index 2.

  4. . Slots 0, 1 and 2 are occupied; slot 3 is empty, so 55 goes to index 3.

  5. All four keys share a home slot, so linear probing builds one cluster of length 4 starting at slot 0. Answer: index 3.

PRACTICE 52 marks · NAT

A hash table uses separate chaining, with each new key inserted at the head of its chain, and its load factor is . Assume simple uniform hashing and a large number of keys, so the term can be ignored. What is the expected number of keys examined in a successful search? Give your answer to two decimal places.

Answer and solution

Answer: (accepted range )

  1. For separate chaining under simple uniform hashing, the expected number of keys examined in a successful search is , which is approximately for large .

  2. Reason: the search examines the target itself (1) plus the keys inserted into the same chain after it. Averaged over all targets, that is keys, less the negligible .

  3. Substitute : .

OFFICIAL GATE 2027 SYLLABUS WORDING

Copied from the GATE 2027 syllabus; see all 2027 syllabi.

GATE CS

Searching, sorting, hashing

GATE DA

hash tables; Search algorithms: linear search and binary search, basic sorting algorithms: selection sort, bubble sort and insertion sort

Preparing in Kolkata? IAE Academy's course for GATE CSE or GATE DA.