[Programming Pearl] Chapter 4: Compile the correct program

Source: Internet
Author: User

1. subscripts: 0 <= l u <= n-1

2. This function can be written as follows:

 
# Include <iostream> using namespace STD; int BS (int * a, int begin, int end, int v) {int * B = a + begin; // start int * E = a + end; // end int * mid = NULL; // The while (B <E) // until it is equal to the first value that appears {mid = B + (e-B)> 1); // obtain the address in the center if (* mid> = V) E = mid; else B = Mid + 1;} If (e-a) <End & (* E = V) Return e-; return-1;} int main () {int A [5] = {1, 2, 2, 4}; cout <BS (A, 0, 4, 2) <Endl; return 0 ;}

Test againCode

# Include <stdio. h> # include <stdlib. h> int CMP (const void * a, const void * B) {return (* (int *) A)-(* (int *) B );} int BS (int * a, int begin, int end, int v) {int * B = a + begin, * E = a + end, * mid = NULL; If (! A) return NULL; while (B <E) {mid = B + (e-B)> 1); If (* mid> = V) E = mid; else if (* mid <v) B = Mid + 1;} If (e-a) <End & (* E = V) Return e-; return-1;} int find (int * a, int begin, int end, int v) {int I = 0; for (I = begin; I <end; ++ I) if (a [I] = V) return I; Return-1 ;}int main (void) {int A [10000]; int n = 10000, I = 0; int F, E; for (I = 0; I <n; ++ I) A [I] = random () % 100; Qsort (A, N, sizeof (INT), CMP); for (I = 0; I <n; ++ I) {f = find (A, 0, n, A [I]); E = BS (A, 0, n, a [I]); If (F! = E) printf ("error find of % d \ n", a [I], F, E) ;}return 0 ;}

6,ProgramEnd-to-End proof: each step will throw at least one bean, so it will always end. In addition, the white beans are either two or not thrown. If the white beans are odd, the white beans are left with a white bean; otherwise, the white beans are black beans.

7. If you want to use binary search in the question, you need to find a lower limit of the number.

Using the method in question 2, you can find the upper bound. Because the line segments are arranged sequentially, you can find the lower bound.

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.