Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

287
Views
How can you optimize linear search if applied on an ordered list of items?

In an unordered list of items, you must check every item until you find a match. How can you optimize linear search if applied on an ordered list of items?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

A linear search has an O(n) time complexity. If the list is known to be ordered, and assuming it supports an O(1) random access (e.g., it's implemented as an array in continuous memory), you could use binary search with a time complexity of O(log(n)).

over 4 years ago · Santiago Trujillo Report

0

If the list is ordered then you could use binary search. Worst-case O(log n) and best case O(1).

Example iterative implementation:

public int binSearch(int[] sortedArr, int k, int l, int h) {
    int i = Integer.MAX_VALUE;

    while (l <= h) {
        int mid = (l + h) / 2;
        if (sortedArr[mid] < k) {
            low = mid + 1;
        } else if (sortedArr[mid] > k) {
            high = mid - 1;
        } else if (sortedArr[mid] == k) {
            i = mid;
            break;
        }
    }
    return i;
}
over 4 years ago · Santiago Trujillo Report

0

If you have an uniform distribution of random numbers you could go all out and use interpolation search

Code from wikipedia

/*
T must implement the operators -, !=, ==, >=, <= and <
such that >=, <=, !=, == and < define a total order on T and
such that

(tm - tl) * k / (th - tl)

is an int between 0 and k (inclusive) for any tl, tm, th in T with tl <= tm <= th, tl != th.

arr must be sorted according to this ordering.

\returns An index i such that arr[i] == key or -1 if there is no i that satisfies this.
*/
template <typename T>
int interpolation_search(T arr[], int size, T key)
{
    int low = 0;
    int high = size - 1;
    int mid;

    while ((arr[high] != arr[low]) && (key >= arr[low]) && (key <= arr[high])) {
        mid = low + ((key - arr[low]) * (high - low) / (arr[high] - arr[low]));

        if (arr[mid] < key)
            low = mid + 1;
        else if (key < arr[mid])
            high = mid - 1;
        else
            return mid;
    }

    if (key == arr[low])
        return low ;
    else
        return -1;
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!