Interpolation search in C: solved exercise

Interpolation search in C: solved exercise

This exercise is scheduled for daily publication and follows the standard site structure: statement, solution, and expected output.

Problem statement

Solve the practical case and verify the console output.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <stdio.h>

int interpolation_search(int a[], int n, int x) {
    int lo = 0, hi = n - 1;
    while (lo <= hi && x >= a[lo] && x <= a[hi]) {
        if (lo == hi) return (a[lo] == x) ? lo : -1;
        int pos = lo + (int)((double)(hi - lo) / (a[hi] - a[lo]) * (x - a[lo]));
        if (a[pos] == x) return pos;
        if (a[pos] < x) lo = pos + 1; else hi = pos - 1;
    }
    return -1;
}

int main(void) {
    int a[] = {10,20,30,40,50,60};
    printf("Indice: %d\n", interpolation_search(a, 6, 40));
    return 0;
}

Expected output

1
Indice: 3

Common mistakes

  • Not validating standard-function return values.
  • Ignoring edge cases for indices, pointers, or buffers.
  • Skipping example-based test runs before publishing.

Practical use

Interpolation search outperforms binary search on uniformly distributed arrays, such as databases sorted by value.

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

Is this exercise useful for C exams and technical interviews?

Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.

Where can I keep practicing with more solved C exercises?

In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

How should I practice this exercise type to improve faster?

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.