diff --git a/Exercise_1.java b/Exercise_1.java index c3ff1141..20c96d3e 100644 --- a/Exercise_1.java +++ b/Exercise_1.java @@ -1,8 +1,25 @@ +//Time Complexity: O(logn) +//Space Complexity: O(1) 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 + if(r>=l){ + int mid= l+(r-l)/2; + + if (arr[mid]==x) + return mid; + + if(arr[mid]>x) + return binarySearch(arr, l, mid-1, x); + + return binarySearch(arr, mid+1, r, x); + + } + return -1; + + } // Driver method to test above diff --git a/Exercise_2.java b/Exercise_2.java index d0b5fa5f..2cb1d943 100644 --- a/Exercise_2.java +++ b/Exercise_2.java @@ -1,3 +1,6 @@ +//Time Complexity: O(nlogn) +//Space Complexity: O(logn) + class QuickSort { /* This function takes last element as pivot, @@ -8,11 +11,26 @@ class QuickSort 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=high; + int s=low; + for(int i =low;i<=high;i++){ + if(arr[i] Array to be sorted, @@ -22,6 +40,13 @@ void sort(int arr[], int low, int high) { // Recursively sort elements before // partition and after partition + //Base Case + if(low st=new Stack<>(); + st.push(l); + st.push(h); + while (!st.isEmpty()) { + h=st.pop(); + l=st.pop(); + //set pivot element to its correct position + + int p= partition(arr, l, h); + //if elementes on left side of pivot, push left side to stack + if(p-1>l){ + st.push(l); + st.push(p-1); + } + //if elements on right side, push right side to stack + if(p+1