Question: Look for the median of 5 numbers, 5 numbers may have the same number, assuming that the number is stored in a[0] a[1] a[2] a[3] a[4], in order to easily remember as A0,A1,A2,A3,A4
Idea: Define the Compare_swap (int* a,int* B) method, this method compares the size of a A, a two number, if a is greater than B to exchange two number, that is, the smaller of two number is stored in a, the larger person is stored in B. Compare in the following order:
Compare A0 A1 with smaller ones A0
Compare A2 A3 with smaller ones A2
Compare A0 A2, save the smaller to A0, if A0 and A2 exchange, then Exchange A1,A3 at the same time, in order to make A0,A1 and a2,a3 still maintain the original size relationship. After these three comparisons, the A0 is smaller than the A1,A2,A3, it is not possible to be the median, so the elimination of A0, (5 Number of the median can not be less than three numbers)
Compare A1 A4 with smaller ones A1
Compare A1 A2, save the smaller to A1, and if the A1 and A2 Exchange, Exchange a3,a4 at the same time, so that the size relationship between A1 A4 and A2 A3 remains the same. After these three comparisons, A1 is smaller than a2,a3,a4 and can be ruled out A1.
Compare A2 A4 and save the smaller ones to A2. This time A2 is the median number.
The code is implemented as follows:
#include <stdio.h>void compare_swap (int *a,int *b) {//Compare and Exchange methods if (*a>*b) {int temp = *a;*a = *b;*b = temp;}} void swap (int *a,int *b) {int temp = *a;*a = *b;*b = temp;} Look for the median of 5 digits, 6 times the method of comparison int find_median_in_five (int a[]) {int temp;compare_swap (&a[0],&a[1]); Compare_swap (& A[2],&A[3]); temp = A[0];compare_swap (&a[0],&a[2]); Exclude A[0]if (temp! = A[0]) swap (&a[1],&a[3]); Compare_swap (&a[1],&a[4]); temp = A[1];compare_swap (& A[1],&A[2]); Exclude A[1]if (temp! = A[1]) swap (&a[3],&a[4]); Compare_swap (&a[2],&a[4]); return a[2];} void Main () {int a[] = {4,11,1,72,11};p rintf ("%d\n", Find_median_in_five (A));}
Looking for the median of 5 numbers, just 6 comparisons, ideas and implementations