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

Add BinarySeach.java #77

Open
wants to merge 3 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
Binary file removed BinarySearch.class
Binary file not shown.
42 changes: 42 additions & 0 deletions BinarySearch.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
public class BinarySearch {

// Binary search function
public static int binarySearch(int[] array, int target) {
int left = 0;
int right = array.length - 1;

while (left <= right) {
int mid = left + (right - left) / 2;

// Check if the target is present at mid
if (array[mid] == target) {
return mid;
}

// If the target is greater, ignore left half
if (array[mid] < target) {
left = mid + 1;
}
// If the target is smaller, ignore right half
else {
right = mid - 1;
}
}

// Target not found in the array
return -1;
}

// Main method to test binary search
public static void main(String[] args) {
int[] sortedArray = {2, 5, 8, 12, 16, 23, 38, 45, 56, 72};
int target = 23;
int result = binarySearch(sortedArray, target);

if (result == -1) {
System.out.println("Element not present in the array");
} else {
System.out.println("Element found at index: " + result);
}
}
}
22 changes: 22 additions & 0 deletions fibonacci.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// C++ program to print first n terms of the Fibonacci series:

#include <iostream>

using namespace std;

int main()
{
int n;
cin >> n;

int a = -1, b = 1, c;
for (int i = 0; i < n; ++i)
{
c = a + b;
a = b;
b = c;

cout << c << ' ';
}
return 0;
}
43 changes: 43 additions & 0 deletions sieve_of_eratosthenes.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#include <iostream>
#include <vector>

using namespace std;

void sieve (vector<bool>& isPrime)
{
int upperLimit = isPrime.size() - 1;

isPrime[0] = isPrime[1] = false;
for (int i = 2; i*i <= upperLimit; ++i)
{
if (isPrime[i])
{
for (int j = i*i; j <= upperLimit; j += i)
{
isPrime[j] = false;
}
}
}
}

int main()
{
cout << "Enter the number till which you want to know all the primes: ";
int userInput;
cin >> userInput;

vector<bool> isPrime (userInput + 1, true);
sieve (isPrime);

cout << "All the primes till " << userInput << ": " << endl;
for (int currentNumber = 2; currentNumber <= userInput; ++currentNumber)
{
if (isPrime[currentNumber])
{
cout << currentNumber << ' ';
}
}
cout << endl;

return 0;
}