Google Interview Question:quicksort-like Questions

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.