Advertisement
fr1sk

bSarch&qSort

Apr 6th, 2016
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.77 KB | None | 0 0
  1. #include<stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int cmp(const void *a, const void *b){
  5.   int *x = (int*)a;
  6.   int *y = (int*)b;
  7.   return *x - *y;
  8. }
  9.  
  10. int cmpBsearch(const void *a, const void *b){
  11.   int *x = (int*)a;
  12.   int *y = (int*)b;
  13.   if(*x>*y){
  14.     return 1;
  15.   }
  16.   else if(*x<*y){
  17.     return -1;
  18.   }
  19.   else{
  20.     return 0;
  21.   }
  22. }
  23.  
  24. int main(){
  25.   int niz[] = {5, 4, 12 ,15, 3, 1, 7};
  26.   int x=12;
  27.   int n=7;
  28.   int i;
  29.   for(i=0; i<7; i++){
  30.     printf("%d ",niz[i]);
  31.   }
  32.   printf("\n");
  33.  
  34.   qsort(niz, 7, sizeof(int), cmp);
  35.   for(i=0; i<7; i++){
  36.     printf("%d ",niz[i]);
  37.   }
  38.  
  39.   int *y= bsearch(&x, niz, n, sizeof(int), &cmpBsearch);
  40.   if(y==NULL){
  41.     printf("Ne postoji element 12 u nizu\n");
  42.   }
  43.   else{
  44.     printf("\n%d",y-niz );
  45.   }
  46.   return 0;
  47.  
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement