From 047e975f977ac4a6356849dc527b6071c4f26f01 Mon Sep 17 00:00:00 2001 From: AnubhutiPuppalwar Date: Wed, 29 Jan 2025 18:32:20 -0800 Subject: [PATCH] Done PreCourse-2 --- Exercise_1.java | 20 +++++++++++++++-- Exercise_2.java | 37 +++++++++++++++++++++++++++++--- Exercise_3.java | 16 ++++++++++++++ Exercise_4.java | 44 ++++++++++++++++++++++++++++++++++++-- Exercise_5.java | 57 +++++++++++++++++++++++++++++++++++++++++++++---- 5 files changed, 163 insertions(+), 11 deletions(-) diff --git a/Exercise_1.java b/Exercise_1.java index c3ff1141..97c3b94f 100644 --- a/Exercise_1.java +++ b/Exercise_1.java @@ -1,8 +1,24 @@ +// Time Complexity : O(logn) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + +//prune the left side if x>arr[mid] else prune the right side. 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; + }else if(x>arr[mid]) { + l=mid+1; + }else { + r=mid-1; + } + } + return -1; } // Driver method to test above @@ -11,7 +27,7 @@ public static void main(String args[]) BinarySearch ob = new BinarySearch(); int arr[] = { 2, 3, 4, 10, 40 }; int n = arr.length; - int x = 10; + int x = 40; int result = ob.binarySearch(arr, 0, n - 1, x); if (result == -1) System.out.println("Element not present"); diff --git a/Exercise_2.java b/Exercise_2.java index d0b5fa5f..6a3c246c 100644 --- a/Exercise_2.java +++ b/Exercise_2.java @@ -1,3 +1,9 @@ +// Time Complexity : O(nlogn) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + + class QuickSort { /* This function takes last element as pivot, @@ -7,12 +13,31 @@ class QuickSort pivot and all greater elements to right of pivot */ void swap(int arr[],int i,int j){ - //Your code here + int t=arr[i]; + arr[i]=arr[j]; + arr[j]=t; } int partition(int arr[], int low, int high) { - //Write code here for Partition and Swap + int pivot=arr[low]; + int i=low+1; + int j=high; + while(i=low && arr[j]>=pivot) { + j--; + } + if(i Array to be sorted, @@ -21,7 +46,13 @@ 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=l && arr[j]>=pivot) { + j--; + } + if(i> stk=new Stack(); + List p=new ArrayList<>(); + p.add(low); + p.add(high); + stk.push(p); + while(!stk.isEmpty()) { + int x=stk.peek().get(0); + int y=stk.peek().get(1); + stk.pop(); + int pivot=partition(arr,x,y); + if(pivot-1>x) { + List l1=new ArrayList<>(); + l1.add(x); + l1.add(pivot-1); + stk.push(l1); + } + if(pivot+1 l2=new ArrayList<>(); + l2.add(pivot+1); + l2.add(y); + stk.push(l2); + } + } + } // A utility function to print contents of arr