diff --git a/Exercise_1.java b/Exercise_1.java index c3ff1141..fd9e3a6c 100644 --- a/Exercise_1.java +++ b/Exercise_1.java @@ -3,6 +3,14 @@ class BinarySearch { int binarySearch(int arr[], int l, int r, int x) { //Write your code here + int index = -1; + for (int i = l; i<=r; i++){ + if(x == arr[i]){ + index = i; + break; + } + } + return index; } // Driver method to test above diff --git a/Exercise_2.java b/Exercise_2.java index d0b5fa5f..d2e63c00 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 + //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 pivot = arr[high]; + int i = low -1; + for (int j = low; j<=high-1; 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,12 @@ 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= r) { + return; + } + int middle = l + (r-l)/2; + sort(arr, l, middle); + sort(arr, middle+1, r); + merge(arr, l, middle, r); } /* A utility function to print array of size n */ @@ -39,4 +81,4 @@ public static void main(String args[]) System.out.println("\nSorted array"); printArray(arr); } -} \ No newline at end of file +} diff --git a/Exercise_5.java b/Exercise_5.java index 30e82675..96aafd5a 100644 --- a/Exercise_5.java +++ b/Exercise_5.java @@ -1,7 +1,13 @@ class IterativeQuickSort { void swap(int arr[], int i, int j) { - //Try swapping without extra variable + //Try swapping without extra variable + if(arr[i] == arr[j]) { + return; + } + arr[i] = arr[i] + arr[j]; + arr[j] = arr[i] - arr[j]; + arr[i] = arr[i] - arr[j]; } /* This function is same in both iterative and @@ -9,12 +15,43 @@ void swap(int arr[], int i, int j) int partition(int arr[], int l, int h) { //Compare elements and swap. + int pivot = arr[h]; + int i = l -1; + for (int j = l; j<=h-1; j++){ + if(arr[j]<= pivot) { + i++; + swap(arr, i, j); + } + } + swap( arr, i+1, h); + return i+1; } // Sorts arr[l..h] using iterative QuickSort void QuickSort(int arr[], int l, int h) { //Try using Stack Data Structure to remove recursion. + int[] stack = new int[h-l+1]; + + stack[0] = l; + stack[1] = h; + int top = 1; + while(top>=0) { + h = stack[top--]; + l = stack[top--]; + + int p = partition(arr, l, h); + if(p-1>l){ + stack[++top] = l; + stack[++top] = p-1; + } + if(p+1