|
| 1 | +public class NutsAndBoltsMatch |
| 2 | +{ |
| 3 | + //Driver method |
| 4 | + public static void main(String[] args) |
| 5 | + { |
| 6 | + // Nuts and bolts are represented as array of characters |
| 7 | + char nuts[] = {'@', '#', '$', '%', '^', '&'}; |
| 8 | + char bolts[] = {'$', '%', '&', '^', '@', '#'}; |
| 9 | + |
| 10 | + // Method based on quick sort which matches nuts and bolts |
| 11 | + matchPairs(nuts, bolts, 0, 5); |
| 12 | + |
| 13 | + System.out.println("Matched nuts and bolts are : "); |
| 14 | + printArray(nuts); |
| 15 | + printArray(bolts); |
| 16 | + } |
| 17 | + |
| 18 | + // Method to print the array |
| 19 | + private static void printArray(char[] arr) { |
| 20 | + for (char ch : arr){ |
| 21 | + System.out.print(ch + " "); |
| 22 | + } |
| 23 | + System.out.print("n"); |
| 24 | + } |
| 25 | + |
| 26 | + private static void matchPairs(char[] nuts, char[] bolts, int low, |
| 27 | + int high) |
| 28 | + { |
| 29 | + if (low < high) |
| 30 | + { |
| 31 | + int pivot = partition(nuts, low, high, bolts[high]); |
| 32 | + |
| 33 | + |
| 34 | + partition(bolts, low, high, nuts[pivot]); |
| 35 | + |
| 36 | + |
| 37 | + matchPairs(nuts, bolts, low, pivot-1); |
| 38 | + matchPairs(nuts, bolts, pivot+1, high); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + |
| 43 | + private static int partition(char[] arr, int low, int high, char pivot) |
| 44 | + { |
| 45 | + int i = low; |
| 46 | + char temp1, temp2; |
| 47 | + for (int j = low; j < high; j++) |
| 48 | + { |
| 49 | + if (arr[j] < pivot){ |
| 50 | + temp1 = arr[i]; |
| 51 | + arr[i] = arr[j]; |
| 52 | + arr[j] = temp1; |
| 53 | + i++; |
| 54 | + } else if(arr[j] == pivot){ |
| 55 | + temp1 = arr[j]; |
| 56 | + arr[j] = arr[high]; |
| 57 | + arr[high] = temp1; |
| 58 | + j--; |
| 59 | + } |
| 60 | + } |
| 61 | + temp2 = arr[i]; |
| 62 | + arr[i] = arr[high]; |
| 63 | + arr[high] = temp2; |
| 64 | + |
| 65 | + |
| 66 | + return i; |
| 67 | + } |
| 68 | +} |
0 commit comments