Method of division and control: the maximum and minimum value of the Binary Search

Source: Internet
Author: User

Problem: given an array, find the maximum and minimum values.

Use the division and control method to solve the problem:

Binary: divide the array into two groups (there may also be a difference between the number of two arrays), find the greatest values of the two arrays respectively, and divide the separated arrays again, recursively follow these scores and divide the final result. The number of two subarrays is one or two.

The number of sub-arrays is 1: This number is set to the maximum and minimum values.

The number of sub-arrays is 2: Compare the size of the two numbers. A larger number is the maximum value, and a smaller number is the minimum value.

Back-to-Back: return the most value in the Child array, and then compare and copy the parent array of the Child array. In this way, the final maximum value and minimum value are obtained.

 

 
Source codeCase:
# Include <stdio. h> void maxmin (int A, int B, int * min, int * max); int array [9] = {1, 3, 4, 5, 6, 7, 8, 9, 2 }; main () {int _ max, _ min; maxmin (0, 8, & _ min, & _ max); printf ("MAX: % d, Min: % d ", _ max, _ min);} void maxmin (int A, int B, int * min, int * max) {int Lmax, Lmin, rmax, rmin; if (A = B) * min = * max = array [a]; else if (a = b-1) {If (array [a] <array [B]) {* min = array [a]; * max = array [B];} else {* min = array [B]; * max = array [a];} else {int mid = (a + B)/2; maxmin (A, mid, & Lmin, & Lmax); maxmin (Mid + 1, B, & rmin, & rmax); If (Lmin <rmin) * min = Lmin; else * min = rmin; If (rmax <Lmax) * max = Lmax; else * max = rmax ;}}

 

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.