The largest element in the collection of divide and conquer actions, and the collection of divide and conquer actions

Source: Internet
Author: User

The largest element in the collection of divide and conquer actions, and the collection of divide and conquer actions

Question: Enter n and then enter n integers. Use the divide and conquer method to calculate the largest element in the n number;

Train of Thought: divide the number of columns into two halves, recursively go down, stop when there is only one number left, return this number, if not one number, return the larger number of the two segments to be divided;

Experiment tip: Find the largest element in the n Data Element Set. When n = 2, you can find the maximum and minimum elements of the two data elements after a comparison. When n> 2, n data elements can be divided into roughly equal two halves, with n/2 data elements in half and n/2 data elements in the other half. Find the largest element in each group, and compare the two largest elements to obtain the largest element of n.

 

The Code is as follows:

# Include <iostream> # include <algorithm> # include <stdio. h> # include <string. h> # include <math. h> # include <stdlib. h> # include <set> # include <queue> # include <vector> using namespace std; int calc (int a [], int l, int r) {if (l = r) return a [l]; return max (calc (a, l, (l + r)/2), calc (, (l + r)/2 + 1, r);} int main () {int a [1005]; int n; cout <"sequence length: "<endl; scanf (" % d ", & n); if (n = 0) {puts (" the sequence length cannot be 0! "); Return 0 ;}cout <" enter a sequence: "<endl; for (int I = 0; I <n; I ++) scanf ("% d", & a [I]); printf ("the largest element of this series is: % d \ n", calc (a, 0, n-1 )); return 0 ;}

 

Related Article

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.