Advertisement
AnhVan1712

TimKiemNhiPhanBangDequy

Mar 15th, 2020
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. #include <stdio.h>
  2. int timKiem(int n, int A[], int x, int nho);
  3. void nhap(int& n, int A[100], int& x);
  4. void xuat(int kq);
  5. void main()
  6. {
  7. int n, A[100], x;
  8. nhap(n, A, x);
  9. int nho = n;
  10. int kq = timKiem(n, A, x,nho);
  11. xuat(kq);
  12. }
  13. void nhap(int& n, int A[100], int& x)
  14. {
  15. printf("Nhap so luong cua mang !\n");
  16. do
  17. {
  18. scanf("%d", &n);
  19. if (n <= 0)
  20. {
  21. printf("nhap khong hop le, hay nhap lai !\n");
  22. }
  23. } while (n <= 0);
  24. printf("Nhap lan luot cac gia tri cua mang theo thu tu tu nho den lon !\n");
  25. for (int i = 0; i < n; i++)
  26. {
  27. scanf("%d", &A[i]);
  28. }
  29. printf("Nhap gia tri can tim kiem !\n");
  30. scanf("%d", &x);
  31. }
  32. int timKiem(int n, int A[], int x, int nho)
  33. {
  34. int tam = A[n / 2];
  35. if (x == tam)
  36. {
  37. return n / 2;
  38. }
  39. else
  40. {
  41. if (n/2 <1||n/2>nho)
  42. {
  43. return -1;
  44. }
  45. if (x < tam)
  46. {
  47. return timKiem(n- 1, A, x,nho);
  48. }
  49. else
  50. {
  51. return timKiem(n+ 1, A, x,nho);
  52. }
  53. }
  54. }
  55. void xuat(int kq)
  56. {
  57. if (kq == -1)
  58. {
  59. printf("Khong tim thay trong mang.\n");
  60. }
  61. else
  62. {
  63. printf("Gia tri can tim o vi tri %d trong mang.\n ", kq);
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement