Advertisement
Petar123

petrovkod

Oct 22nd, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>
  4. #include<math.h>
  5. void swap(float *p1, float *p2){
  6. float temp;
  7. temp = *p1;
  8. *p1 = *p2;
  9. *p2 = temp;
  10. }
  11. void gen_arr(float *p, int n, float dg, float gg){
  12. int i;
  13. for (i = 0; i < n; i++){
  14. p[i] = dg + (float)rand() / RAND_MAX*(gg - dg);
  15. }
  16. }
  17.  
  18. int sekv_pret(float *p, int n, float x){
  19. int i,a=-1;
  20. for (i = 0; i < n; i++){
  21. if (p[i] == x){
  22. a = i;
  23. break;
  24. }
  25. }
  26. return a;
  27. }
  28.  
  29. void sort(float p[], int low,int high){
  30. int s = p[(low + high) / 2];
  31. int i = low, j = high;
  32. while (i <= j) {
  33. while (p[i] < s) {
  34. i++;
  35. }
  36. while (p[j] > s)
  37. {
  38. j--;
  39. }
  40. if (i <= j) {
  41. swap(&p[i], &p[j]);
  42. i++;
  43. j--;
  44. }
  45. }
  46. }
  47.  
  48. int bin_pret(float p[], int n, float x){
  49. int dg=0, gg=n-1,s,a=-1;
  50. while (dg <= gg){
  51. s = (dg + gg) / 2;
  52.  
  53. if (x == p[s]){
  54. printf("Broj je pronađen na %d. mjestu.", s);
  55. a = s;
  56. break;
  57. }
  58. else if (x > p[s]){
  59. dg = s + 1;
  60. }
  61. else if (x < p[s]) {
  62. gg = s - 1;
  63. }
  64. }
  65. return a;
  66. }
  67.  
  68. int main(){
  69. int n,x;
  70. float *p,dg,gg;
  71. time_t t1, t2;
  72.  
  73. srand(time(NULL));
  74.  
  75. printf("\nUnesite velicinu polja:");
  76. scanf("%d", &n);
  77.  
  78. p = (float*)malloc(n*sizeof(float));
  79.  
  80. printf("\nUnesite donju i gornju granicu polja:");
  81. scanf("%f%f", &dg, &gg);
  82.  
  83. gen_arr(p, n, dg, gg);
  84.  
  85. printf("\nUnesite x:");
  86. scanf("%d", &x);
  87.  
  88. t1 = clock();
  89. int sp = sekv_pret(p, n, x);
  90. t2 = clock();
  91. if (sp == -1)
  92. printf("\nBroj se ne nalazi u polju.");
  93. else printf("\nBroj se nalazi na %d mjestu.", sp + 1);
  94. printf("\nVrijeme trajanja sekvencijalnog pretrazivanja je:%d ms\n", t2 - t1);
  95.  
  96. t1 = clock();
  97. sort(p, 0,n-1);
  98. t2 = clock();
  99. printf("\nVrijeme trajanja sortiranja je:%d ms\n", t2 - t1);
  100.  
  101. t1 = clock();
  102. int bp = bin_pret(p, n, x);
  103. t2 = clock();
  104. if (bp == -1)
  105. printf("\nBroj se ne nalazi u polju.");
  106. else printf("\nBroj se nalazi na %d mjestu.", sp + 1);
  107. printf("\nVrijeme trajanja brinarnog pretrazivanja je:%d ms", t2 - t1);
  108.  
  109. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement