diff --git a/BinarySearch.class b/BinarySearch.class deleted file mode 100644 index bcdbf9d..0000000 Binary files a/BinarySearch.class and /dev/null differ diff --git a/BinarySearch.java b/BinarySearch.java new file mode 100644 index 0000000..9a9aec3 --- /dev/null +++ b/BinarySearch.java @@ -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); + } + } +} diff --git a/fibonacci.cpp b/fibonacci.cpp new file mode 100644 index 0000000..0726967 --- /dev/null +++ b/fibonacci.cpp @@ -0,0 +1,22 @@ +// C++ program to print first n terms of the Fibonacci series: + +#include + +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; +} \ No newline at end of file diff --git a/sieve_of_eratosthenes.cpp b/sieve_of_eratosthenes.cpp new file mode 100644 index 0000000..3288efb --- /dev/null +++ b/sieve_of_eratosthenes.cpp @@ -0,0 +1,43 @@ +#include +#include + +using namespace std; + +void sieve (vector& 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 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; +} \ No newline at end of file