Professional Documents
Culture Documents
1)A
#include <bits/stdc++.h>
using namespace std;
int recursivebinarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return recursivebinarySearch(arr, l, mid - 1, x);
return recursivebinarySearch(arr, mid + 1, r, x);
}
return -1;
}
int main()
{
int arr[]={2,4,10,44,23,11,22};
int x = 10;
int n=sizeof(arr)/sizeof(arr[0]);
int result = recursivebinarySearch(arr, 0, n - 1, x);
(result == -1)
? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
1B)
#include <bits/stdc++.h>
using namespace std;
int binarySearch(int arr[], int l, int r, int x)
{
while (l <=r) {
int m = l + (r - l) / 2;
if (arr[m] == x)
return m;
if (arr[m] < x)
l = m + 1;
else
r = m - 1;
}
return -1;
}
int main(void)
{
int arr[]={2,4,10,44,23,11,22};
int x = 10;
int n=sizeof(arr)/sizeof(arr[0]);
int result = binarySearch(arr, 0, n - 1, x);
(result == -1)
? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
Output:
2)
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
//Non-Recursive
cout << "Factorial of " << n << " is: " << fact << endl;
//Recursive
cout << "Factorial of " << n << " is: " << factorial(n) << endl;
Output:
3)
#include <iostream>
using namespace std;
int main()
{
int n,arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
n=sizeof(arr)/sizeof(arr[0]);
quickSort(arr, 0, n - 1);
Output: