Implementierung von C lower_bound

Basiert auf der folgenden definition gefunden hier

Gibt einen iterator zeigt auf das
erste element in der sortierten Palette
[first,last), die nicht zu vergleichen
weniger als Wert. Der Vergleich ist
mit einer operator< für die
erste version, oder comp für die zweite.

Was wäre die C gleichwertige Umsetzung von lower_bound(). Ich verstehe, dass es wäre eine Modifikation der binären Suche, aber kann nicht scheinen, um ganz lokalisieren der genauen Umsetzung.

int lower_bound(int a[], int lowIndex, int upperIndex, int e);

Beispiel:

int a[]= {2,2, 2, 7 };

lower_bound(a, 0, 1,2) would return 0 --> upperIndex is one beyond the last inclusive index as is the case with C++ signature.

lower_bound(a, 0, 2,1) would return 0.

lower_bound(a, 0, 3,6) would return 3;
lower_bound(a, 0, 4,6) would return 3; 

Mein versuchter code ist unten angegeben:

int low_bound(int low, int high, int e)
{
    if ( low < 0) return 0;
    if (low>=high )
    {
      if ( e <= a[low] ) return low;
      return low+1;
    }
    int mid=(low+high)/2;
    if ( e> a[mid])
        return low_bound(mid+1,high,e);
    return low_bound(low,mid,e);

}

InformationsquelleAutor der Frage Shamim Hafiz | 2011-06-22

Schreibe einen Kommentar