The previous article summarizes Mergesort-like questions, which summarizes the questions about Quicksort.
Question:
Given an array of object A, and an array of object B. All A ' s has
Different sizes, and all B ' s has different sizes. Any object A is of the
Same size as exactly one object B. We have a function f (A, B) to compare the
Size of one A and one B. But we cannot compare between A ' s or B ' s.
Give an algorithm to match each A with each B.
Brute Force's practice time complexity is O (n^2). The essence of this problem is to use quicksort for matching, with an average time complexity of O (Nlog (N)). Because the same array cannot be compared, you need to select an element in an array, divide it as the pivot of another array, and then recursively until all the elements correspond. This problem is also called matching nuts & bolts.
Public classMatchingnutsandbolts { Public Static voidMain (String arcg[]) {int[] nuts = {3,1,5,2,6,4}; int[] bolts = {5,1,2,6,4,3}; Matchpairs (Nuts,bolts,0,nuts.length-1); System.out.println (arrays.tostring (nuts)); System.out.println (arrays.tostring (bolts)); } Public Static voidMatchpairs (int[] Nuts,int[] Bolts,intLowintHigh ) { if(Low <High ) { intPivot =partition (Nuts, low, High, bolts[low]); Partition (bolts, low, high, nuts[pivot]); Matchpairs (Nuts, bolts, low, pivot-1); Matchpairs (nuts, bolts, pivot+1, high); } } Public Static intPartitionint[] Array,intLowintHighintpivot) { intI=low,j =High ; while(i<=j) { if(Array[i] >pivot) {Swap (array, I, j); J--; } Else if(Array[i] <pivot) {i++; } Else{Swap (array, low, i); I++; }} swap (array, low, I-1); returnI-1; } Public Static voidSwapint[] Array,intIintj) { intTMP =Array[i]; Array[i]=Array[j]; ARRAY[J]=tmp; }}
Google Interview Question:quicksort-like Questions