What is the fastest search method for a sorted array?

前端 未结 8 581
伪装坚强ぢ
伪装坚强ぢ 2021-02-01 04:57

Answering to another question, I wrote the program below to compare different search methods in a sorted array. Basically I compared two implementations of Interpolation search

8条回答
  •  滥情空心
    2021-02-01 05:54

    Posting my current version before the question is closed (hopefully I will thus be able to ehance it later). For now it is worse than every other versions (if someone understand why my changes to the end of loop has this effect, comments are welcome).

    int newSearch(int sortedArray[], int toFind, int len) 
    {
        // Returns index of toFind in sortedArray, or -1 if not found
        int low = 0;
        int high = len - 1;
        int mid;
    
        int l = sortedArray[low];
        int h = sortedArray[high];
    
        while (l < toFind && h > toFind) {
            mid = low + ((float)(high - low)*(float)(toFind - l))/(1+(float)(h-l));
    
            int m = sortedArray[mid];
    
            if (m < toFind) {
                l = sortedArray[low = mid + 1];
            } else if (m > toFind) {
                h = sortedArray[high = mid - 1];
            } else {
                return mid;
            }
        }
    
        if (l == toFind)
            return low;
        else if (h == toFind)
            return high;
        else
            return -1; // Not found
    }
    

提交回复
热议问题