Recently, in the book "Introduction to the algorithm", in the practice of finding a problem: the use of binary search method to achieve the insertion order, because the previous content has explained the recursive implementation of the dichotomy, so in this will be combined to hope to solve the problem. Gossip not much to say, directly on the code:
//Algrithms.cpp: Defines the entry point of the console application. ////use the dichotomy to complete the insertion sort, and use the recursive algorithm to complete the two-point method#include"stdafx.h"intBinary_divide (intA[],intLowintHeightintkey) { //The condition of the recursive termination is the height of the input low> input, when the position is found to the left or right of the low//It is only necessary to determine the size between key and A[low] to determine where the key should be placed if(Low >height) { if(Key >A[low]) { returnLow +1;//if key is larger than A[low], then key is placed in the next position of A[low] } Else{ returnLow//if key is smaller than a[low], then key is placed above the position of A[low] (because the program will then empty the location) } } if(a[(low + height)/2] >key) {Binary_divide (A, Low,+ height)/2-1, key); }Else{binary_divide (A, ( Low+ height)/2+1, height, key); }}int_tmain (intARGC, _tchar*argv[]) { inta[ One] = {6,Ten, -,3,7, -, -, -,1,3,6};//sorted Array intArray_length =sizeof(a)/sizeof(a[0]);//Array Size intKey//Key Words//Insert A[n] into the number of pre-ordered n-1 for(inti =1; i < array_length; i++) {Key=A[i]; intj = i-1; intPosition = Binary_divide (A,0, J, key);//the dichotomy to find out where key is supposed to be//position (including position) until the number of J moves back one position while(J >=0&& j>=position) { if(a[j]>key) {A[j+1] =A[j]; } J--; } A[position]= key;//put the keyword in the right place//The array is printed on the position of each good one element for(intK =0; K < Array_length; k++) {printf ("%d", A[k]); } printf ("%d\n", position);//Print the right location for your search} getchar (); return 0;}
The idea of the algorithm is very simple, but the original linear search is sorted by the appropriate position of the part of the element with the use of dichotomy to find the right position, the previous troubled me for a long time is the recursive termination of the judgment. In the study of binary search, we know that if a number does not exist in an array, the dichotomy will terminate recursion because the lower bound of the input array is greater than the upper bound, and when the algorithm finds its position, this recursive termination of the dichotomy causes us to find a point that is closest to "fit position", So the judgment of the size between this point and the keyword can be transferred back to the correct position.
Rookie one, the first blog, but also invited the Big God in the garden to advise.
Implementation of insertion sorting algorithm by dichotomy (binary method using recursive return)