diff --git a/BinarySearch.java b/BinarySearch.java new file mode 100644 index 0000000..5dabde7 --- /dev/null +++ b/BinarySearch.java @@ -0,0 +1,64 @@ +import java.util.*; + +public class BinarySearch { + // Iterative Binary Search + public static int Iterative(int[] arr, int target) { + int low = 0, high = arr.length - 1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (arr[mid] == target) + return mid; // Element found + else if (arr[mid] < target) + low = mid + 1; + else + high = mid - 1; + } + return -1; // Element not found + } + + // Recursive Binary Search + public static int Recursive(int[] arr, int low, int high, int target) { + if (low > high) + return -1; + int mid = low + (high - low) / 2; + if (arr[mid] == target) + return mid; + else if (arr[mid] > target) + return Recursive(arr, low, mid - 1, target); + else + return Recursive(arr, mid + 1, high, target); + } + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("Enter number of elements: "); + int n = sc.nextInt(); + + int[] arr = new int[n]; + System.out.println("Enter elements in sorted order:"); + for (int i = 0; i < n; i++) { + arr[i] = sc.nextInt(); + } + + System.out.print("Enter target element to search: "); + int target = sc.nextInt(); + + // Iterative version + int resultIterative = Iterative(arr, target); + + // Recursive version + int resultRecursive = Recursive(arr, 0, n - 1, target); + + if (resultIterative != -1) + System.out.println("Element found at index (iterative): " + resultIterative); + else + System.out.println("Element not found (iterative)."); + + if (resultRecursive != -1) + System.out.println("Element found at index (recursive): " + resultRecursive); + else + System.out.println("Element not found (recursive)."); + + sc.close(); + } +} diff --git a/Insertion_Sort.cpp b/Insertion_Sort.cpp new file mode 100644 index 0000000..a60ffe6 --- /dev/null +++ b/Insertion_Sort.cpp @@ -0,0 +1,28 @@ +#include +using namespace std; + +void insertionSort(vector& arr) { + int n = arr.size(); + for (int i = 1; i < n; i++) { + int key = arr[i]; + int j = i - 1; + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j--; + } + arr[j + 1] = key; + } +} +int main() { + int n; + cout << "Enter number of elements: "; + cin >> n; + vector arr(n); + cout << "Enter elements: "; + for (int i = 0; i < n; i++) cin >> arr[i]; + insertionSort(arr); + cout << "Sorted array: "; + for (auto x : arr) cout << x << " "; + cout << endl; + return 0; +}