C + + Insert Sort algorithm instance _c language

Source: Internet
Author: User

Insert Sort

Nothing likes to look at the data structure and algorithm, increase their understanding of data structure and algorithms, but also increase their programming skills. The insertion sort is one of the more common sorts, and it is very simple to understand. Now for example, the following data needs to be sorted:

10 3 8 0 6 9 2

When you use Insert sorting for ascending sorting, the steps for sorting are as follows:

10 3 8 0 6 9 2//Take element 3, go to compare with 10

3 10 8 0 6 9 2//due to 10:3, move 10 back, place 3 in the original 10 position, and then take 8 to compare with the previous element 10

3 8 10 0 6 9 2//likewise move 10; then 8 and 3, 8 greater than 3, so no longer move; so repeat.

......

0 2 3 6 8 9 10

That is, each time we take an element, we compare the element to the previously sorted element.

The worst time complexity for inserting a sort is O (n^2). At the same time, the algorithm does not need to open up additional space, it is in the original space to move operations.

Code implementation

Copy Code code as follows:

#include <iostream>
using namespace Std;

void Insertsort (int arr[], int length)
{
int temp;
for (int i = 1; i < length; ++i)//start with the second element in the array
{
temp = Arr[i]; Record the current element
int j = i-1;
while (J >= 0 && Temp < ARR[J])//Compare the current element to a previously sorted sequence element
{
Arr[j + 1] = Arr[j]; The sorted sequence is moved back in the whole.
--j;
}
Arr[j + 1] = temp; Inserts the current element
}
}

int main ()
{
int arr[10] = {9, 2, 8, 2, 3, 2, 4, 10, 34, 5};

Insertsort (arr, 10);

for (int i = 0; i < ++i)
{
cout<<arr[i]<< "";
}
cout<<endl;

return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.