Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- int timKiem(int n, int A[], int x, int nho);
- void nhap(int& n, int A[100], int& x);
- void xuat(int kq);
- void main()
- {
- int n, A[100], x;
- nhap(n, A, x);
- int nho = n;
- int kq = timKiem(n, A, x,nho);
- xuat(kq);
- }
- void nhap(int& n, int A[100], int& x)
- {
- printf("Nhap so luong cua mang !\n");
- do
- {
- scanf("%d", &n);
- if (n <= 0)
- {
- printf("nhap khong hop le, hay nhap lai !\n");
- }
- } while (n <= 0);
- printf("Nhap lan luot cac gia tri cua mang theo thu tu tu nho den lon !\n");
- for (int i = 0; i < n; i++)
- {
- scanf("%d", &A[i]);
- }
- printf("Nhap gia tri can tim kiem !\n");
- scanf("%d", &x);
- }
- int timKiem(int n, int A[], int x, int nho)
- {
- int tam = A[n / 2];
- if (x == tam)
- {
- return n / 2;
- }
- else
- {
- if (n/2 <1||n/2>nho)
- {
- return -1;
- }
- if (x < tam)
- {
- return timKiem(n- 1, A, x,nho);
- }
- else
- {
- return timKiem(n+ 1, A, x,nho);
- }
- }
- }
- void xuat(int kq)
- {
- if (kq == -1)
- {
- printf("Khong tim thay trong mang.\n");
- }
- else
- {
- printf("Gia tri can tim o vi tri %d trong mang.\n ", kq);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement