For the median, O (n) Java implementation "Using quick sort binary to find the median"

Source: Internet
Author: User

To find the median of an unordered array, it is convenient to use a counting sort to get the time complexity O (n), which discusses how to locate using a quick sort.

1, the median definition

2. Algorithm idea

3. Java Code Implementation

4. Analysis of Time complexity

5. Appendix

The median is defined in two general ways:

The first type:

The value of the middle position of the sorted array, and if the number of arrays is an even number, the number of N/2 of the sorted array is returned.

The first Kind (official):

The value of the middle position of the sorted array, and if the number of arrays is an even number, the average of the most intermediate two digits is returned.

For example: {7, 9, 4, 5} the first output 5; The second output 6.0

algorithm thought : Everyone should know that the quick sort each lie can locate a number in the final position of this array, so it can be used to locate any one position in a set of binary method.

The method is: After a trip to the partition end, the location of the position and the location to be positioned to compare, if not equal, then the partition interval binary, until equal, return the value of this position

Java code Implementation :

Because the second median definition needs to be positioned at two locations, the first extension is possible, so first one is discussed:

1      Public Static intGetmedian (int[] nums) {2         returnPartition (nums, 0, Nums.length-1);3     }4 5     Private Static intPartition (int[] Nums,intStartintend) {6         /*** Quick Row partition function original code--start***/7         intleft =start;8         intright = end + 1;9 Ten         intPoint =Nums[start]; One          while(true) { A              while(Left < right && Nums[--right] >=Point ) -                 ; -              while(Left < right && Nums[++left] <=Point ) the                 ; -             if(left = =Right ) { -                  Break; -}Else { +                 intTMP =Nums[left]; -Nums[left] =Nums[right]; +Nums[right] =tmp; A             } at         } -Nums[start] =Nums[left]; -Nums[left] =Point ; -         /*** Quick Row partition function original code--end***/ -          -         /*** Positioning judgment * **/ in         if(left = = (nums.length-1)/2) { -             returnNums[left]; to}Else if(Left > (nums.length-1)/2) { +             returnPartition (Nums, start, left-1); -}Else { the             returnPartition (Nums, left + 1, end); *         } $}

In fact, the original partition after the end of adding a positioning to judge, at this time left point is already the number of this trip positioning, if there is no successful positioning will be the upper and lower bounds to adjust the binary.

"Note": "If the number of arrays is an even number, then returns the number of N/2 of the sorted array" This sentence needs to use (nums.length-1)/2 to achieve the subscript of this sentence, and to meet the odd time to take the most intermediate subscript effect.

Time complexity Analysis :

Since this method is also recursive, it must conform to the recursive complexity of the pass-term expression: T (n) = at (n/b) + f (n)

Where a for each recursion will be divided into a number of the next layer to be computed, (n/b) The number of elements to be calculated for the next layer, F (n) is the computational complexity of this layer

Because it is a binary lookup, there are: A=1, b=2 (average), f (n) =n (each time the traversal is compared to the interchange)

So there are

T (n) = t (N/2) +n        =  T (N/4) + N/2 +n        ...         = T (1) + 2 + ... + n/2 +n    //  T (1) ≈1 geometric series summation        = (1-N * 2)/(1-2)        = 2n-1

So the last average time complexity is O (n)

"B=n complexity O (n) under optimal conditions;

Worst case b=n-1/n, i.e. (n/b) = (n-1), when the complexity is O (N2), please calculate the ha "

Appendix --The realization of the second kind of finding the median

Idea: The first one has solved the positioning of a number, and the second is to locate two numbers, because the positioning of a number can not guarantee that another number is sorted, so you need to recall the method

Then move the part of the method that is positioned to make a getbyquicksort (int[] nums,int stop)

Java Code Implementation:

1      Public Static DoubleGetbyquicksort (int[] nums,intstop) {2         if(Stop < 0 | | Stop >=nums.length) {3             Throw Newindexoutofboundsexception ();4         }5         6         intStart = 0;7         intEnd = Nums.length-1;8         intpar = 0;9         Ten          while(Start <=end) { OnePar =partition (Nums, start, end); A             if(Par = =stop) { -                  Break; -}Else if(Par >stop) { theEnd = Par-1; -}Else { -start = par + 1; -             } +         } -         returnNums[par]; +}

Here's partition (...) method is the last section of the code in the partition method of the /*** * * * * * * * * * * * * minus, and then add a return to the left ; can be.

And find the median number and then write a method getMedian2 (...) Judge the parity, and then call Getbyquicksort (...). You can do it:

1      Public Static DoublegetMedian2 (int[] nums) {2         if(nums.length% 2 = = 1) {3             returnGetbyquicksort (Nums, NUMS.LENGTH/2);4}Else {5             return(Getbyquicksort (Nums, NUMS.LENGTH/2-1) +6Getbyquicksort (Nums, NUMS.LENGTH/2)/2.0;7         }8}

For the median, O (n) Java implementation "Using quick sort binary to find the median"

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.