Minimum Absolute Difference in a Sorted Array in C
Finding the minimum absolute difference between elements is a common problem in programming and interviews.
When the array is sorted, we can solve this efficiently by comparing only adjacent elements.
In this tutorial, we will implement an optimized solution in C.
Concept Overview
In a sorted array, the smallest difference will always be between two neighboring elements.
So instead of comparing all pairs, we just compare adjacent elements.
Problem Statement
Given a sorted array, find the minimum absolute difference between any two elements.
Example
Input:
Array: 1 3 6 10 15
Output:
Minimum Difference: 2
Approach
1. Initialize min_diff with a large value.
2. Traverse the array from index 1 to n-1.
3. Compute difference between arr[i] and arr[i-1].
4. Update min_diff if smaller difference is found.
5. Return the minimum difference.
C Program
#include <stdio.h>
#include <limits.h>
int minAbsDiff(int arr[], int n) {
int min_diff = INT_MAX;
for (int i = 1; i < n; i++) {
int diff = arr[i] - arr[i - 1];
if (diff < min_diff) {
min_diff = diff;
}
}
return min_diff;
}
int main() {
int arr[] = {1, 3, 6, 10, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int result = minAbsDiff(arr, n);
printf("Minimum Absolute Difference: %d", result);
return 0;
}
Output
Minimum Absolute Difference: 2
Detailed Explanation
Since the array is sorted, the smallest difference must be between consecutive elements.
The loop checks each adjacent pair and keeps track of the smallest difference.
This avoids unnecessary comparisons and improves performance.
Time and Space Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Applications
Used in optimization problems and data analysis.
Helpful in clustering and nearest-neighbor searches.
Advantages
Very efficient due to linear traversal.
Simple logic with minimal comparisons.
Limitations
Works only for sorted arrays.
Requires sorting first if input is unsorted.
Improvements You Can Make
Modify the program to also return the pair with minimum difference.
Handle unsorted arrays by sorting first.
Extend to find k minimum differences.
Understanding this problem helps build efficient solutions for many array-based algorithms.
Codecrown