constk

Lab6_Task4_BinarySearch

Nov 27th, 2019
262
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include "stdio.h"
  3. #include <iostream>
  4.  
  5. int main() {
  6. setlocale(0, "Russian");
  7.  
  8. const int N = 8;
  9. short A[N] = {-9, -8, -6, 0, 4, 5, 6, 10}, lN = 0, rN = N - 1, len, standart, n;
  10. bool goOut = false;
  11.  
  12. //for (int i = 0; i < N; i++) {
  13. // printf("A[%d] = ", i);
  14. // scanf("%hd", &A[i]);
  15. //}
  16. //puts("");
  17.  
  18. for (int i = 0; i < N; i++) {
  19. for (int j = 0; j < N - 1; j++) {
  20. if (A[j] > A[j + 1]) {
  21. short t = A[j];
  22. A[j] = A[j + 1];
  23. A[j + 1] = t;
  24. }
  25. }
  26. }
  27.  
  28. printf("Введите элемент, который хотите найти: ");
  29. scanf("%hd", &standart);
  30.  
  31. while (!goOut) {
  32. len = rN - lN;
  33. n = len / 2 + lN;
  34.  
  35. if (standart < A[n]) {
  36. rN = n - 1;
  37. }
  38. if (standart > A[n]) {
  39. lN = n + 1;
  40. }
  41. if (standart == A[n]) {
  42. printf("Элемент найден на %d позиции\n", n);
  43. goOut = true;
  44. }
  45. if (standart != A[n] && len < 1) {
  46. printf("Такого элемента нет\n");
  47. goOut = true;
  48. }
  49.  
  50. }
  51.  
  52. system("pause");
  53. return 0;
  54. }
RAW Paste Data