Add solutions for searching.
This commit is contained in:
parent
3ed0108d81
commit
4fc992890a
@ -5,7 +5,19 @@
|
||||
|
||||
int *binsucheZgr(int suchElem, int *startZgr, int *endZgr)
|
||||
{
|
||||
// TODO
|
||||
while(startZgr <= endZgr)
|
||||
{
|
||||
int *mitte = startZgr + (endZgr - startZgr) / 2;
|
||||
|
||||
if(suchElem < *mitte)
|
||||
endZgr = mitte - 1;
|
||||
else if(suchElem > *mitte)
|
||||
startZgr = mitte + 1;
|
||||
else
|
||||
return mitte;
|
||||
}
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int *binsuche(int suchElem, int array[], unsigned int anzahl)
|
||||
|
||||
@ -42,7 +42,7 @@ int main()
|
||||
srand(0);
|
||||
|
||||
fuelleArray(zufallszahlen, ANZAHL, MIN, MAX);
|
||||
// TODO: Sortierung mit qsort
|
||||
qsort(zufallszahlen, ANZAHL, sizeof(zufallszahlen[0]), vergleiche);
|
||||
|
||||
gibArrayAus(zufallszahlen, MAX_100(ANZAHL));
|
||||
|
||||
@ -60,7 +60,7 @@ int main()
|
||||
anzahlVorkommen = zaehleVorkommenBs(suchZahl, zufallszahlen, ANZAHL);
|
||||
|
||||
printf("Die Zahl %d ist %dx enthalten. (%lf Sekunden)\n", suchZahl, anzahlVorkommen, messeZeitInSek());
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@ -74,3 +74,49 @@ void gibArrayAus(int array[], int anzahl)
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
int vergleiche(const void *arg1, const void *arg2)
|
||||
{
|
||||
return *(const int *)arg1 - *(const int *)arg2;
|
||||
}
|
||||
|
||||
int zaehleVorkommenNaiv(int suchElem, int array[], int anzahl)
|
||||
{
|
||||
int vorkommen = 0;
|
||||
|
||||
for(int i = 0; i < anzahl && array[i] <= suchElem; i++)
|
||||
{
|
||||
if(array[i] == suchElem)
|
||||
vorkommen++;
|
||||
}
|
||||
|
||||
return vorkommen;
|
||||
}
|
||||
|
||||
int zaehleVorkommenBs(int suchElem, int array[], int anzahl)
|
||||
{
|
||||
int vorkommen = 0;
|
||||
|
||||
int *pos = binsuche(suchElem, array, anzahl);
|
||||
|
||||
if(pos != NULL)
|
||||
{
|
||||
int *start = pos;
|
||||
int *ende = array + anzahl - 1;
|
||||
|
||||
while(*start == suchElem && start <= ende)
|
||||
{
|
||||
vorkommen++;
|
||||
start++;
|
||||
}
|
||||
|
||||
start = pos-1;
|
||||
|
||||
while(*start == suchElem && start >= array)
|
||||
{
|
||||
vorkommen++;
|
||||
start--;
|
||||
}
|
||||
}
|
||||
|
||||
return vorkommen;
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user