diff --git a/Exercise_1.java b/Exercise_1.java index c3ff1141..998d16b6 100644 --- a/Exercise_1.java +++ b/Exercise_1.java @@ -3,6 +3,27 @@ class BinarySearch { 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(arr[mid] < x) + { + l = mid + 1; + } + + else + { + r = mid - 1; + } + } + + return -1; } // Driver method to test above diff --git a/Exercise_2.java b/Exercise_2.java index d0b5fa5f..72bd7cc7 100644 --- a/Exercise_2.java +++ b/Exercise_2.java @@ -6,22 +6,50 @@ class QuickSort smaller (smaller than pivot) to left of 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 + //Write code here for Partition and Swap + int i = low-1; + + for(int j = low; j < high; j++) + { + if(arr[j] < arr[high]) + { + i += 1; + swap(arr, i, j); + } + } + + swap(arr, i+1, high); + + return i+1; + } + /* The main function that implements QuickSort() arr[] --> 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 + // Recursively sort elements before + // partition and after partition + if(low st = new Stack(); + st.push(new int[] {l,h}); + + while(!st.isEmpty()) + { + int[] boundary = st.pop(); + int low = boundary[0], high = boundary[1]; + + if(low