Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

First commit #366

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 46 additions & 35 deletions Binary_Search.cpp
Original file line number Diff line number Diff line change
@@ -1,46 +1,57 @@

#include <iostream>
#include <algorithm> // For std::sort
using namespace std;
int lin(int arr[],int n,int key){
int low=0;
int high=n-1;
int num;

while(low<=high)
{
num=(low+high)/2;
if(key==arr[num])
return num;
else if(key<arr[num]){
high=num-1;
}
// if(key>num){
else{
low=num+1;

int lin(int arr[], int n, int key) {
int low = 0;
int high = n - 1;

while (low <= high) {
int mid = (low + high) / 2;
if (key == arr[mid]) {
return mid;
} else if (key < arr[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
return -1; // Key not found
}

int main()
{
int key,n,i;
int arr[n];
cout<<"enter range ";
cin>>n;
for(i=0;i<n;i++){
cout<<"eneter the "<<i+1<<" number";
cin>>arr[i];
int main() {
int n;

cout << "Enter the number of elements: ";
cin >> n;

if (n <= 0) {
cout << "Array size must be positive." << endl;
return 1; // Exit if invalid size
}

int* arr = new int[n]; // Dynamically allocate array

for (int i = 0; i < n; i++) {
cout << "Enter element " << i + 1 << ": ";
cin >> arr[i];
}

cout << "Enter the key to search: ";
int key;
cin >> key;

// Sort the array before performing binary search
sort(arr, arr + n);

int index = lin(arr, n, key);
if (index == -1) {
cout << "The number you entered is not in the array." << endl;
} else {
cout << "The number is found at index: " << index << endl;
}
//int num
cout<<"enter the key ";
//cin>>key;
int data=lin(arr,n,5);
if(data==-1)
cout<<"the number you entered is out of scope";
else
cout<<"the number is placed at "<<data <<"position";
//cout<<"here the num you wants "<<data;

delete[] arr; // Free allocated memory
return 0;
}
Loading