Untitled

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
1.2 kB
4
Indexable
Never
#include<bits/stdc++.h>
#include <cstdlib> // for srand() and rand()
#include <ctime> // for time()
using namespace std;

void phatsinhmang(int arr[],int n);
void xuatMang(int arr[],int n);
int timkiemnhiphan(int arr[], int left, int right , int x);

int main(){
	int n;
	cin >> n;
	int arr[n];
	phatsinhmang(arr,n);
    xuatMang(arr,n);
	int x;
	cout << "Nhap x: ";
	cin >> x;
	int result = timkiemnhiphan(arr,0,n-1,x);
	if (result== -1) cout <<"khong tim thay\n";
	else cout << result;
	return 0;
}
void phatsinhmang(int arr[], int n)
{ 
	srand(time(NULL));
	
	for (int i = 1; i < n; i++)
	{
		//arr[i] = rand();
		 arr[i] = arr[i - 1] + rand() % 100;
		// tang dan khong sap xep.
	}
}
void xuatMang(int arr[], int n)
{
	for (int i = 0; i < n; i++)
	{
		cout << "arr[" << i << "] = " << arr[i] << endl;
	}
}
int timkiemnhiphan(int arr[], int left,int right, int x)
{
     	while (right >=1){
     		int mid = left + (right - left) /2;
     		// tuong duong (left + right ) /2
     		if (arr[mid]==x) return mid;
     		if (arr[mid]>x) right = mid -1;
     		if (arr[mid]<x) left = mid + 1;
     	}
     	return -1;
}