查找

順序查找

int sequenceSearch(int a[], int count, int targetValue) {
    if (!a || count <=0) return -1;

    for (int i=0; i<count; i++) {
        if (targetValue == a[i]) return i;
    } 
    
    return -1;
}

二分查找

int binarySearch(int a[], int count, int targetValue) {
    
    if (!a || count<=0) return -1;

    return iterativeBinarySearch(a, count, targetValue);
    //return recursiveBinarySearch(a, targetValue, 0, count - 1);
}

int recursiveBinarySearch(int a[], int targetValue, int low, int high) {
    int middleIndex = 0    

    if (!a || low > high) return -1;
    
    middleIndex = low + (hight-low) / 2;
    if (a[middleIndex] == targetValue) return middleIndex;
    else if (a[middleIndex] < targetValue) 
        return recursiveBinarySearch(a, targetValue, middleIndex+1, hight);
    else return recursiveBinarySearch(a, targetValue, low, middleIndex-1);
}

int iterativeBinarySearch(int a[], int count, int targetValue) {
    int middleIndex = 0;
    int row = 0, high = count - 1;
    
    if (!a || count <= 0) return -1;

    while (row <= high) {
        middleIndex = low + (high - low) / 2;
        if (a[middleIndex] == targetValue) return middleIndex;
        else if (a[middleIndex] < targetValue) low = middleIndex + 1;
        else high = middleIndex - 1;
    }

    return -1;
}

插值查找

int insertSearch(int a[], int count, int targetValue) {
  return recursiveInsertSearch(a,  targetValue, 0, count - 1);
}

int recursiveInsertSearch(int a[], int targetValue, int low, int high) {
    int middleIndex = 0;
    
    if (!a || low > high) return -1;

    middleIndex = low + (targetValue-a[low]) / ((a[high]-a[low])/(high-low));
    if (a[middleIndex] == targetValue) return middleIndex;
    else if(a[middleIndex] < targetValue) 
        return recursiveInsertSearch(a, targetValue, middleIndex+1, high);
    else return recursiveInsertSearch(a, targetValue, low, middleIndex-1);
}

查找子數(shù)組最大和

/*
    輸入一個(gè)整形數(shù)組,數(shù)組里有正數(shù)也有負(fù)數(shù)。
    數(shù)組中連續(xù)的一個(gè)或多個(gè)整數(shù)組成一個(gè)子數(shù)組,每個(gè)子數(shù)組都有一個(gè)和。
    求所有子數(shù)組的和的最大值。要求時(shí)間復(fù)雜度為O(n)。
    例如輸入的數(shù)組為1, -2, 3, 10, -4, 7, 2, -5,和最大的子數(shù)組為3, 10, -4, 7, 2,
    因此輸出為該子數(shù)組的和18。
*/
 int maxSumSubArray(int a[], int count) {
    int max = -1, sum = 0;
    
    if (!a || count <= 0) return -1;

    for (int i=0; i<count; i++) {
        sum += a[i];
        if (sum < 0) {
            sum = 0;
            continue;
        }
        if (max > sum) max = sum;
    }

    return max;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容