Advertisement
Guest User

tipo nd musu prototipas

a guest
May 21st, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <iostream>
  3. #include <fstream> //reikalinga, norint nuskaityti duomenis is failo ir irasyti juos i faila
  4. void skaitymas (int &n, int arr[]);
  5. //-----------------------------
  6.  
  7. using namespace std;
  8.  
  9.  
  10. int binarySearch(int arr[], int l, int r, int x) // l - pirmas elementas, r - paskutinis, x - ieskomas elementas
  11. {
  12. while (l <= r)
  13. {
  14. int m = l + (r-l)/2;
  15.  
  16. // Patikrina ar elementas nera vidurinis
  17. if (arr[m] == x)
  18. return m;
  19.  
  20. // Jeigu x didesnis, ignoruoja visa kaire puse
  21. if (arr[m] < x)
  22. l = m + 1;
  23.  
  24. // Jeigu x mazesnis, ignoruoja visa desine puse
  25. else
  26. r = m - 1;
  27. }
  28.  
  29. // Jeigu atsiduriame cia , elementas neegzistuoja
  30. return -1;
  31. }
  32.  
  33. int main(void)
  34. {
  35. ofstream rf ("rezultatai.txt");
  36.  
  37. int arr[100],j;
  38. int n = sizeof(arr)/ sizeof(arr[0]);
  39. int x ;
  40. skaitymas (j, arr);
  41. cout << "Iveskite ieskoma elementa: " ;
  42. cin >> x;
  43.  
  44. int result = binarySearch(arr, 0, n-1, x);
  45. if (result == -1){
  46. rf << "Toks elementas neegzistuoja";
  47. }
  48. else rf << "Toks elementas egzistuoja, jo numeris: " << result+1 << endl;
  49.  
  50. rf.close(); //failas uzdaromas
  51. return 0;
  52. }
  53. //-----------------------------
  54. void skaitymas (int &j, int arr[])
  55. {
  56. ifstream df("duomenys.txt");
  57. df>>j;
  58. for(int i = 0; i<j; i++)
  59. df>>arr[i];
  60. df.close();
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement