diff --git a/Exercise_1.java b/Exercise_1.java index c3ff1141..840a919a 100644 --- a/Exercise_1.java +++ b/Exercise_1.java @@ -1,9 +1,21 @@ class BinarySearch { // Returns index of x if it is present in arr[l.. r], else return -1 int binarySearch(int arr[], int l, int r, int x) - { - //Write your code here - } + { + while(l<=r){ + int mid = l + (r-l)/2; + + if(arr[mid] == x){ + return mid; + } + if(arr[mid] < x){ + l = mid+1; + }else{ + r = mid-1; + } + } + return -1; + } // Driver method to test above public static void main(String args[]) diff --git a/Exercise_2.java b/Exercise_2.java index d0b5fa5f..97ddbc83 100644 --- a/Exercise_2.java +++ b/Exercise_2.java @@ -7,12 +7,25 @@ class QuickSort pivot and all greater elements to right of pivot */ void swap(int arr[],int i,int j){ - //Your code here + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; } int partition(int arr[], int low, int high) - { - //Write code here for Partition and Swap + { + int pivot = arr[high]; + int i = low - 1; + + for (int j = low; j < high; j++) { + if (arr[j] < pivot) { + i++; + swap(arr, i, j); + } + } + + swap(arr, i + 1, high); + return i + 1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, @@ -21,7 +34,14 @@ int partition(int arr[], int low, int high) void sort(int arr[], int low, int high) { // Recursively sort elements before - // partition and after partition + // partition and after partition + + if (low < high) { + int pi = partition(arr, low, high); + + sort(arr, low, pi - 1); + sort(arr, pi + 1, high); + } } /* A utility function to print array of size n */ diff --git a/Exercise_3.java b/Exercise_3.java index 1f9b752a..6738c538 100644 --- a/Exercise_3.java +++ b/Exercise_3.java @@ -16,10 +16,23 @@ class Node /* Function to print middle of linked list */ //Complete this function - void printMiddle() - { + void printMiddle() + { //Write your code here //Implement using Fast and slow pointers + if(head == null){ + System.out.println("List is empty"); + return; + } + + Node slow = head; + Node fast = head; + + while(slow != null && fast != null){ + slow = slow.next; + fast = fast.next.next; + } + System.out.println("Middle element" + slow.data); } public void push(int new_data) diff --git a/Exercise_4.java b/Exercise_4.java index 81afd3c2..65f3b180 100644 --- a/Exercise_4.java +++ b/Exercise_4.java @@ -5,7 +5,47 @@ class MergeSort // Second subarray is arr[m+1..r] void merge(int arr[], int l, int m, int r) { - //Your code here + //Your code here + int n1 = m-l+1; + int n2 = r-m; + + int[] L = new int[n1]; + int[] R = new int[n2]; + + for(int i = 0;i stack = new Stack<>(); + + stack.push(l); + stack.push(h); + + while (!stack.isEmpty()) { + + h = stack.pop(); + l = stack.pop(); + + int p = partition(arr, l, h); + + if (p - 1 > l) { + stack.push(l); + stack.push(p - 1); + } + + if (p + 1 < h) { + stack.push(p + 1); + stack.push(h); + } + } + } + // A utility function to print contents of arr void printArr(int arr[], int n) {