diff --git a/Exercise_1.java b/Exercise_1.java index c3ff1141..48ae7ea6 100644 --- a/Exercise_1.java +++ b/Exercise_1.java @@ -1,8 +1,25 @@ -class BinarySearch { +/* +Space Complexity O(1) no extra space used +Time Complexity O(log(n)) where n is the no of elements in the array + */ +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 + int mid=0; + while(l<=r) { + mid=l+(r-l)/2; + if(arr[mid]==x) + return mid; + if(x Array to be sorted, - low --> Starting index, + + 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-1;j++){ + if(arr[j] Array to be sorted, + low --> Starting index, high --> Ending index */ - void sort(int arr[], int low, int high) - { - // Recursively sort elements before - // partition and after partition - } - + void sort(int arr[], int low, int high) + { + // Recursively sort elements before + // partition and after partition + if(low < high) { + int partition = partition(arr,low,high); + sort(arr,low,partition-1); + sort(arr,partition+1,high); + } + } + /* A utility function to print array of size n */ - static void printArray(int arr[]) - { - int n = arr.length; - for (int i=0; i"); + tnode = tnode.next; + } + System.out.println("NULL"); + } - public void printList() - { - Node tnode = head; - while (tnode != null) - { - System.out.print(tnode.data+"->"); - tnode = tnode.next; - } - System.out.println("NULL"); - } - - public static void main(String [] args) - { - LinkedList llist = new LinkedList(); - for (int i=15; i>0; --i) - { - llist.push(i); - llist.printList(); - llist.printMiddle(); - } - } -} \ No newline at end of file + public static void main(String [] args) + { + LinkedList llist = new LinkedList(); + for (int i=15; i>0; --i) + { + llist.push(i); + llist.printList(); + llist.printMiddle(); + } + } +} \ No newline at end of file diff --git a/Exercise_4.java b/Exercise_4.java index 81afd3c2..958435a9 100644 --- a/Exercise_4.java +++ b/Exercise_4.java @@ -1,42 +1,84 @@ -class MergeSort -{ - // Merges two subarrays of arr[]. - // First subarray is arr[l..m] - // Second subarray is arr[m+1..r] - void merge(int arr[], int l, int m, int r) - { - //Your code here - } - - // Main function that sorts arr[l..r] using - // merge() - void sort(int arr[], int l, int r) - { + +/* +Time Complexity n(log(n)) +Space Complexity O(n) temporary array +*/ +class MergeSort +{ + // Merges two subarrays of arr[]. + // First subarray is arr[l..m] + // Second subarray is arr[m+1..r] + void merge(int arr[], int l, int m, int r) + { + //Your code here + int len1=m-l+1; + int len2=r-m; + + int[] left=new int[len1]; + int[] right=new int[len2]; + + for(int i=0;i=0){ + h=aux[top--]; + l=aux[top--]; + int partition=partition(arr,l,h); + + if(l