Chapter algorithm base

Insertion Sort

Insertion sort works like many people arranged in one hand and playing cards. Initially, our left hand is empty and the next card face on the table. Then, every time we take a card off the table and insert it into the correct position in the left hand. To find the correct location of a card, right to left, we will compare it with each card already in hand, as shown in Fig.

 Code

template<class T>
void InsertionSort(T a[], int nums) {
    for (int i = 1; i < nums; i++) {
        T key = a[i];
        int j = i - 1;
        while (j >= 0 && a[j] > key) {
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;
    }
}

 

Divide and Conquer

Many useful algorithms in the structure is recursive: in order to solve a given problem, one or more algorithms recursively calls itself to solve a number of sub-issues closely related. These algorithms typically follow the idea of ​​divide and conquer: the original problem into several smaller-scale but similar to the original problem of sub-problems, to solve these sub-problems recursively, and then combine the solutions of these sub-issues to establish the original problem solution .

Partition at each recursive model has three steps :

  • Decompose the original problem into several sub-problems, these sub-problems are smaller examples of the original problem.
  • Solve these sub-problems, recursively solving each sub-problem. Then, if the size of sub-problems is small enough, direct solution.
  • The combined solution of these sub-solution of the problem to the original problem.

Merge sort algorithm in full compliance with sub-rule mode. Intuitively operates as follows:

  • Decomposition : The sequence has n elements to be sorted into two sub-sequences each having n / 2 elements.
  • Solution : merge sort recursively two aligned sequences.
  • Merge : merge two sequences sorted.

When the length of the sequence to be sorted is 1, recursive "began to rise," do not do any work in this case, because the length of each sequence have been sorted.

Code

template<class T>
void Merge(T a[], int p, int q, int r) {
    int n1 = q - p + 1, n2 = r - q;
    T *left = new T[n1 + 1], *right = new T[n2 + 1];
for (int i = 0; i < n1; i++) { left[i] = a[p + i]; } left[n1] = max; for (int i = 0; i < n2; i++) { right[i] = a[q + i + 1]; } right[n2] = max;
int i = 0, j = 0; for (int k = p; k <= r; k++) { if (left[i] < right[j]) { a[k] = left[i]; i++; } else { a[k] = right[j]; j++; } } }
template
<class T> void MergeSort(T a[], int p, int r) { if (p < r) { int q = (p + r) / 2; MergeSort(a, p, q); MergeSort(a, q + 1, r); Merge(a, p, q, r); } }

 

Guess you like

Origin www.cnblogs.com/bjxqmy/p/12498525.html