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);
- int szukanie_binarne(int tab[], int n, int x);
- int * sort(int tab[],int n);
- int main(){
- int ilosc = 2;
- int i;
- int * indeks = 0;
- int tab[10] = {1,4,7,6,10,4,5,2,3,9};
- sort(tab,10);
- for(i = 0; i < 10; i++){
- printf("%d ",tab[i]);
- }
- printf("\n%d\n",szukanie_liniowe_1(tab,10,4));
- indeks = szukanie_liniowe_2(tab,10,4,&ilosc);
- for(i = 0; i < ilosc; i++){
- printf("%d ",indeks[i]);
- }
- printf("\n%d",szukanie_binarne(tab,10,4));
- getchar();
- return 0;
- }
- 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 * index = 0;
- *ilosc = 0;
- for(i = 0; i < n; i++){
- if(tab[i] == x) {
- index = realloc(index,++(*ilosc)*sizeof(int));
- index[(*ilosc) - 1] = i;
- }
- }
- return index;
- }
- int szukanie_binarne(int tab[], int n, int x){
- int l = 0, r = n - 1, mid;
- while(1){
- if(l <= r){
- mid = (l+r)/2;
- if(tab[mid] == x)
- return mid;
- else if(tab[mid] < x)
- l = mid + 1;
- else if(tab[mid] > x)
- r = mid - 1;
- }
- else
- return -1;
- }
- }
- int * sort(int tab[], int n){
- int i,j,key;
- for(i = 2; i < n; i++){
- key = tab[i];
- j = i - 1;
- while(j > 0 && tab[j] > key){
- tab[j+1] = tab[j];
- j = j - 1;
- }
- tab[j+1] = key;
- }
- return tab;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement