Get the App
SLTechnology News&Howtos  ›  Development  › 

How to implement the insertion sort of C++ sorting algorithm

Shulou Source: shulou.com Published: 2022-05-31 22:12:51 09月20日 Update

Most people do not understand the knowledge points of this article "how to achieve the insertion sorting of the C++ sorting algorithm", so the editor summarizes the following contents for you. The content is detailed, the steps are clear, and it has a certain reference value. I hope you can get something after reading this article, let's take a look at this "C++ sorting algorithm insertion sorting how to achieve" article.

1. The basic idea: insert the unsorted data elements into the sorted data sequence in order of size, and scan the unsorted data from back to front in the sorted sequence to find the corresponding position and insert it.

For example: insert sort 2, 4, 3, 1, 6, 5. Before sorting, the default 2 is ordered, which is an ordered area, while 4, 3, 1, 6, 5 is disordered and disordered. Insert the five unordered numbers into the ordered area in order from small to large.

The first sort: compare 4 with 2 in the ordered area. if it is less than 2, it will be inserted in front of 2, and greater than 2 will be inserted after 2. The ordered area after operation is: {2pcm4}

The second sequence: compare 3 with each number of the ordered area (from right to left, that is, with the number of the ordered area) to find the appropriate position to insert. After the operation, the ordered area is: {2mine3j4}. Here insert 3 between 2 and 4.

……

The fifth sorting: compare the data element 5 with the data in the ordered area, and insert it into the ordered area, then the sorted data sequence is: {1mem2magin3, 4pyrr5, 6}.

Summary:

1. The first data element in the unordered area is ordered by default on the first sort.

two。 As can be seen from the above example, if you sort the number of n, you need to do (nMub 1) trip.

two。 Code:

# includeusing namespace std;void insertion_sort (int a [], int len) {int I, j, temp; for (I = 1; I

< len; i++) //控制趟数 { temp = a[i]; for(j = i; j >

0 & & temp < a [j-1]; jmurt -) / / compare the data of the disordered region with the data elements of the ordered region {a [j] = a [j] = a [j-1]; / move the elements of the ordered area back} a [j] = temp;}} int main () {int a [] = {2,4,3,1,6,5}; insertion_sort (a, 6); for (int I = 0; I < 6; iSum +) {cout

Tags: Sorting ordering data elements situation content algorithm order clocking that is sequence best complex from small to large small location complexity article time number of times Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Microsoft vpn Shulou Information Xiaomi