Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- int szukanie_liniowe_1(int TAB[], int n, int x);
- int *szukanie_liniowe_2(int TAB[], int n, int x, int *ilosc);
- void czytaj_tab(int *t, int n);
- void sortuj(int *t, int n);
- void drukuj_tab(int *t, int n);
- int szukanie_binarne(int TAB[], int n, int x);
- int main()
- {
- int n, pos;
- int *t, *indeksy, ilosc, i, x;
- ilosc=0;
- printf("Podaj n:");
- scanf("%d", &n);
- t=NULL;
- t=(int*)realloc(t, n*sizeof(int));
- czytaj_tab(t, n);
- printf("Podaj x:");
- scanf("%d", &x);
- pos = szukanie_liniowe_1(t, n, x);
- if(pos>=0)
- {
- printf("\nZnaleziono na pozycji: %d", pos);
- indeksy = szukanie_liniowe_2(t, n, x, &ilosc);
- printf("\nZnalezione pozycje w szukanie_liniowe_2:");
- for(i=0; i<ilosc; i++)
- printf(" %d", *(indeksy+i));
- sortuj(t, n);
- drukuj_tab(t, n);
- pos = szukanie_binarne(t, n, x);
- printf("\nZnaleziono na pozycji: %d", pos);
- }
- else
- printf("\nBrak szukanej wartosci");
- getch();
- }
- void czytaj_tab(int *t, int n)
- {
- int i;
- t=(int*)realloc(t, n*sizeof(int));
- for(i=0; i<n; i++)
- {
- printf("Podaj %d element: ", i+1);
- scanf("%d", (t+i));
- }
- }
- void sortuj(int *t, int n)
- {
- int i, j, temp;
- for (i = 0; i<n-1; i++)
- {
- for (j=0; j<n-1-i; j++)
- {
- if (t[j] > t[j+1])
- {
- temp = t[j+1];
- t[j+1] = t[j];
- t[j] = temp;
- }
- }
- }
- }
- int szukanie_liniowe_1(int TAB[], int n, int x)
- {
- int i;
- for (i=0; i<n; i++)
- {
- if (*(TAB+i)==x)
- return i;
- }
- return -1;
- }
- int *szukanie_liniowe_2(int TAB[], int n, int x, int *ilosc)
- {
- int i;
- int *indeksy;
- *ilosc = 0;
- indeksy = NULL;
- for (i=0; i<n; i++)
- {
- if (*(TAB+i)==x)
- {
- indeksy = (int*)realloc(indeksy, (*ilosc+1)*sizeof(int));
- *(indeksy + *ilosc)=i;
- (*ilosc)++;
- }
- }
- return indeksy;
- }
- void drukuj_tab(int *t, int n)
- {
- int i;
- for (i=0; i<n; i++)
- printf("\n%d", *(t+i));
- }
- int szukanie_binarne(int TAB[], int n, int x)
- {
- int left=0, right=n-1, mid;
- while(left<=right)
- {
- mid=(left+right)/2;
- if (*(TAB+mid)==x)
- return mid;
- else
- {
- if (TAB[mid]<x)
- left=mid;
- else
- right=mid;
- }
- }
- return -1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement