|
| 1 | +package sorting; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by dheeraj on 7/9/2016. |
| 5 | + */ |
| 6 | +public class NutsAndBolts { |
| 7 | + |
| 8 | + private static int getPartition(char[] array, int start, int end, char pivotValue) { |
| 9 | + //end pivot |
| 10 | + int index = start; |
| 11 | + for (int x = start; x <= end - 1; x++) { |
| 12 | + if (array[x] < pivotValue) { |
| 13 | + char xxx = array[x]; |
| 14 | + array[x] = array[index]; |
| 15 | + array[index] = xxx; |
| 16 | + index++; |
| 17 | + } else if (array[x] == pivotValue) { |
| 18 | + //to maintain end pivot |
| 19 | + char xxx = array[end]; |
| 20 | + array[end] = pivotValue; |
| 21 | + array[x] = xxx; |
| 22 | + } |
| 23 | + } |
| 24 | + char xxx = array[index]; |
| 25 | + array[index] = array[end]; |
| 26 | + array[end] = xxx; |
| 27 | + return index; |
| 28 | + } |
| 29 | + |
| 30 | + public static void main(String[] strings) { |
| 31 | + char[] nuts = new char[]{'a', 'b', 'd', 'c'}; |
| 32 | + char[] bolts = new char[]{'b', 'a', 'd', 'c'}; |
| 33 | + matchPairs(nuts, bolts, 0, nuts.length - 1); |
| 34 | + System.out.println(nuts); |
| 35 | + System.out.println(bolts); |
| 36 | + } |
| 37 | + |
| 38 | + private static void matchPairs(char[] nuts, char[] bolts, int low, |
| 39 | + int high) { |
| 40 | + if (low < high) { |
| 41 | + int l = getPartition(nuts, low, high, bolts[high]); |
| 42 | + getPartition(bolts, low, high, nuts[l]); |
| 43 | + matchPairs(nuts,bolts,low,l-1); |
| 44 | + matchPairs(nuts,bolts,l+1,high); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + |
| 49 | +} |
0 commit comments