Bubble, direct insertion, fast, four kinds of understanding merge sort, as well as feelings of practical applications.

 

Operating environment All the following programs are Code :: Block, code running in different compiler, results may vary

For example, the position of the following definitions of the variables are not all at the beginning of the program, on the VC, can cause an error. Correction: The program to define variables statement at the beginning of the program can be.

************************************************************************************************************************************************************************************************

Man of few words said, directly to the question:

A): direct insertion sort (there are many types of insertion sort, the talk usually the most widely used)

Code for output as follows :( Example positive sequence, reverse the output, only the code can be modified appropriately)

#include <bits / STDC ++ H.> 
#include <algorithm> 
the using namespace STD; 

int A [100055]; 

int main () 
{ 
    int n-, I; 
    n-CIN >>; 

    for (I =. 1; I <= n-; I ++) 
    { 
        CIN >> A [I]; 
    } 

    int head; 
    head = 2; 
    the while (head <= n-) 
    { 
        I = head; 
        the while (I> = 2 && A [I] <A [I-. 1]) 
        { 
            IF (a [i] <a [ i-1]) // determines whether switching 
            { 
                swap (A [I], A [I-. 1]); // call the function swap 
                i--; 
            } 
        } 
        head ++; // since the role of the index, is a range of circulating plus 1 
    } 
 
    for (I =. 1; I <= n-;i++)
    {
        cout<<a[i];
    }
    return 0;
}

Run the code above is:

 

First, let's haircut ideas above code, the code above is actually a time while cycling compared for a [2] and a [1]  a [3] and a [2], a [2] and a [ . 1] ; a [. 4] with a [3], a [3 ] and a [2], a [2 ] and a [1]; ......... size, until all elements of the array been traversed, is finished Sort.

We can summarize the above code into a model, i.e., the above code can sort any set of data for any period of continuous data (only necessary to change the initialization condition, and end condition of the loop code can be realized) , and this idea a typical example is " rolling list " problem.

Of course, the above code can also be used for-loop, but think, while loop, which is thought to better reflect the nature, in particular by a variable head, reflect the conversion of the comparison range. And, in practice, the personal feeling, with a while loop to achieve more convenient.

2): The Bubble Sort

Code is as follows (in normal order output example)

#include<bits/stdc++.h>
#include<algorithm>
using namespace std;

int a[55];

int main()
{
    int n,i;
    cin>>n;
    for(i=1;i<=n;i++)
    {
        cin>>a[i];
    }

    int head = 1;
    while(head<=n)
    {
        for(i=head+1;i<=n;i++)
        {
            if(a[i]<a[head])
            {
                swap(a[i] ,a[head]);
            }
        }
        head++;
    }

    for(i=1;i<=n;i++)
    {
        cout<<a[i];
    }
    return 0;
}

Run the code above is:

  

Thought the code above are: firstly, by comparison with the remaining elements of the first element of the array, and adjusted to a minimum of the first element; and then, by comparison with the remaining elements of the second element of the array, and the smallest element transferred to the second; and so, when the head is equal to n, the sorting is completed .

Above algorithm, not to engage in competition for students, it should be the most commonly used method of sorting.

The code can also be achieved for loop.

 

C): Quick Sort

Specific code as follows (in ascending order output form)

#include<iostream>
#include<algorithm>
using namespace std;

void quicksort(int l ,int r);

int a[100055];

int main()
{
    int n,i;
    cin>>n;
    for(i=1;i<=n;i++)
    {
        cin>>a[i];
    }

    quicksort(1 ,n);

    for(i=1;i<=n;i++)
    {
        cout<<a[i]<<" ";
    }

    cout<<endl;
    return 0;
}

void quicksort(int l  ,int r)
{
    int i,j,m,mid;
    i = l;
    j = r;
   mid = (l+r)/2; m = a[mid];//将数组分成两部分 while(i<=j) {
/ *********************************************** /
/ / Note here while inside the judge why not bring the condition "="?
// to prevent a period when there are equal numbers of the array appears that the loop becomes an infinite loop. As examples mentioned below. the while (A [I] <m) I ++; the while (A [J]> m) J,;
/ ************************************************************ ************************************************************ / IF (I <= J) { the swap (A [I], A [J]); I ++; J,; } } IF (JL> =. 1) // stop determination conditions calling function itself quicksort (l, j); // itself, to separate the two parts, by calling the function sorting
// Meanwhile, since i, j through while loops are crossed value mid, therefore, a new range (l, j), the following (i, r) Similarly. if (ri> = 1) // stop calling function itself determination conditions quicksort (i, r); // itself, to separate the two parts, by calling the function to sort }

Run the code above results:

 

However, when the determination condition in the while loop band equal sign, there will be loopholes, may render the program loop, such as:

 

The code bipartite actually reflects the idea: first random number in a selected array, a random array divided into two parts (here, I will use the value interval corresponding to an intermediate position, in fact, may generate a random position with rand function , this is actually more reasonable), respectively, in the left and right removal greater than or equal, less than or equal to a [mid] number, exchange, until i, j over the mid value, the cycle ends. So constantly circulating, which can ultimately achieve the sort.

 Quick sort essence lies in the flexible application binary thoughts, it is also one of its high operating efficiency reasons it is.

 

D): merge sort

Code is as follows :( Example ascending order)

#include<bits/stdc++.h>
using namespace std;
#define N 100055
void mergesort(int l, int r);
A int [N];
int larray [N], RArray [N], RN, LN, lposition, rPosition; // larray [N], RArray [N] for two arrays stored optically resolved;
                                                  // LN ;, for recording the number of rn is divided into right and left, respectively, comprising an array element
                                                  positions // lposition, rposition for an array of records in the table where
int main()
{
   int n,i;
   cin>>n;
   for(i=1;i<=n;i++)
       cin>>a[i];
   mergesort(1,n);
   for(i=1;i<=n;i++)
        {
            cout<<a[i]<<" ";
        }
       cout<<endl;
       return 0;
}
void mergesort(int l,int r)
{
   int i;
   int mid=(l+r)/2;
        // array into two parts
   if (l <mid)
    mergesort (l, mid); // call the function itself repeatedly, implements sorting
   if (mid + 1 <r)
    mergesort (mid + 1, r); // call the function itself repeatedly, implement sorting
 
   ln=rn=0;
   for(i=l;i<=mid;i++)
         larray[++ln]=a[i];
   for(i=mid+1;i<=r;i++)
         rarray[++rn]=a[i];
 
   = =. 1 rPosition lposition;
         for (I = L; I <= R & lt; I ++)
        {
// **************************** ************************************************** /
// this section is used to solve the last element of the ownership of the array (because for one element of the array after the chase, had no other elements to be compared with his size, then, it can not take advantage of the following statements, by comparing the two size of array elements in which the dispensing position. in this case,
// statements must be designed separately, allocation position for the final element, and will have the following two statements)
            IF (lposition> LN)
              a [I] = rarray [rposition ++]; // lposition > ln means, the current position of the target array beyond the effective length of the array, the same below.
       IF the else (rPosition> RN)
              A [I] = larray [lposition ++];
// **************************** **************************************************************** /
     the else IF (larray [lposition] <= RArray [rPosition]) // this is two assigned position of the element in the array, a small value is assigned to the principle of the dispensing position, the same below.
               A [I] = larray [lposition ++];
     the else
        A [I] = RArray [rPosition ++];
    }
}

  Run the code above results:

The core idea of this code is: first use of an array of multiple dichotomous thinking bisected, and then from each small group to get copies of pairwise follow the merger at the same time in ascending order, ultimately, to implement sorting .

Specific picture is as follows :( The following diagram is taken from Baidu Encyclopedia, link: https: //baike.baidu.com/pic/ merge sort / 1639015/0 / c8177f3e6709c93d673b9ed49d3df8dcd00054c3

fr=lemma&ct=single#aid=0&pic=c8177f3e6709c93d673b9ed49d3df8dcd00054c3)

In the several merge sort sort it should be the most complicated sort, but its high operating efficiency, as well as the important thought of it contains makes qualified as a programmer, or engage in competition students must master algorithm.

So far, personal feeling, the application of the above ideas merge sort algorithm is undoubtedly the best place of the classic " logarithm of the number of reverse order " problem.

 

E) a binary search

Besides introducing the above-mentioned four common methods of sorting, but I would like to add something about the dichotomy find something. (After a number is added to a set of numbers which identify its location in this group of numbers)

Look at the code in order to achieve positive sequence input :( Example)

#include<iostream>
using namespace std;
const int maxint = 1000000000;
main int ()
{
    int A [100055];
    int n-, m;
    CIN >> >> n-m;
    int I;
    for (I =. 1; I <= n-; I ++)
    {
        CIN >> A [I];
    }
    a [0] = -maxint;
    a [n-+. 1] = MAXINT; // this is to prevent the effect of the statement by the maximum number of input data is greater than the known instability caused by the program
    int l,r,mid,mark;
    l = 0,r=n+1;
    while(l<=r)
    {
        mid = (l+r)/2;
        if(a[mid]>=m)
        {
            mark = mid;
            r = mid-1;
        }
        else
        {
            l = mid+1;
        }
    }
    cout<<mark<<endl;
    return 0;
}

  Operating results for the above code:

If no such statement will:

The result is garbled! ! !

So, we designed the dichotomy, be sure to consider when the input value is greater than the known maximum this case , of course, the solution to this problem is more than the above one of not one lists.

 

I hope this can be set to help you! ! !

************************************************************************************************************************************************************************************************************************* 

Again, the code above are various ways of learning + their understanding of income, should the infringement, please inform, after verification, it will be deleted immediately! ! !

At the same time it was freshman, the above examples are self-set, as if by mistake, please inform, will be corrected immediately.

I write this article the main purpose is to organize knowledge, but limited to the individual level, such as the contents of the above statements is slightly wrong, or no place where, please inform the chiefs, the next will change immediately! ! !

Welcome bigwigs comments, messages.

Finally, the code word is not easy, and if I feel OK, then, I beg bigwigs point a praise it.

 

 

 

 

Guess you like

Origin www.cnblogs.com/meZRH/p/11886420.html