Introduction to Algorithms - recursion

Recursive procedure is very common in the design, sometimes greatly simplifies the complexity of the problem solved.

Here's algorithm 2.3-4 exercises Introduction to the answers.

Concrete is to write a recursive version of insertion sort.

 1 void insert_sort(int a[],int n)
 2 {
 3     if(n==1) return ;
 4     else
 5     {
 6         insert_sort(a,n-1);
 7         int i=n-1,temp=a[n];
 8         while(a[i]>=temp&&i>=1) a[i+1]=a[i],i--;
 9         a[i+1]=temp;
10     }
11 }

Look, the process is very simple.

But be careful wording of this efficiency is very low. Either space or time consuming great.

Recursion formula: t [n] = t [n-1] + cn, so the time of consumption is n ^ 2.

Another point to note, maximum consumption recursion stack space to call it has N stack space, stack space is usually limited, not unlimited free to use the recursive ah. Otherwise, changing the input data can easily lead to system crashes.

Another extension that: 2.3-5 Problem:

Exercise requires us to make an example about ordered binary search.

In the title on the general idea is given. Here I realized all of a sudden in code.

 1 void binary_search(int a[],int le,int ri,int x)
 2 {
 3     while(le<=ri)
 4     {
 5         int mid=(le+ri)/2;
 6         if(a[mid]==x) return mid;
 7         else if(a[mid]<x) le=mid+1;
 8         else ri=mid-1;
 9     }
10     return -1;
11 }
12 
13 int binary_sear(int a[],int le,int ri,int x)
14 {
15     int mid=(le+ri)/2;
16     if(le>ri) return -1;
17     if(a[mid]==x) return mid;
18     else if(a[mid]>x) return binary_sear(a,le,mid-1,x);
19     else return binary_sear(a,mid+1,ri,x);
20  } 

Limited to the above number in the ordered array of binary search detailed search visual circumstances.

As 2.3-6 exercises.

The results clearly not be optimized by the binary search. This is due to defects in the array itself, it can not lead to complete insertion and deletion of data in constant time.

But we can still use binary search to try it.

But I'm not going to try.

Finally, 2.3-7 exercises answer is a bit complicated.

I can think of is to use merge sort, in its traversal of traversal of each layer are trying to use binary search to see if any can match? Time is nlogn

 

Guess you like

Origin www.cnblogs.com/zww-kjj/p/12383187.html