Sorting Algorithm (ii) Insert sorting

Source: Internet
Author: User

Insert sorting:

Traverse arrays from start to end

Compare the current element with all elements before the current element
If the current element is smaller than the previous one, move the current element forward until all elements before the current element are sorted by size

The Code is as follows:

[Html]
Package com. robert. paixu;
 
/**
* Insert sorting
* Sorting from small to large
* @ Author Administrator
*/
Public class InsertSortAlgorithm {

Public static void main (String [] args ){
Int [] arrays = {20,100,-,-, 20, 15 };
InsertSort (arrays );
Display (arrays );
}

/**
* Insert sorting
*/
Private static void insertSort (int [] arrays ){
// Cyclically traverse the Array
Int currentIndex = 0;
Int preIndex = 0;
For (int I = 0; I <arrays. length; I ++)
{
/**
* Comparison between the current element and all elements before the current element
* 1. Move the current element forward until all elements before the current element are sorted by size
*/
CurrentIndex = I;
PreIndex = I-1;
While (currentIndex! = 0 & preIndex> = 0 ){
If (arrays [currentIndex] <arrays [preIndex])
{
Swap (arrays, currentIndex, preIndex );
CurrentIndex --;
}
Else
{
Break;
}
PreIndex --;
}
}
}

Private static void swap (int [] arrays, int currentIndex, int preIndex ){
Int temp = arrays [currentIndex];
Arrays [currentIndex] = arrays [preIndex];
Arrays [preIndex] = temp;
}

/**
* Display the value of the sorted Array
* @ Param arrays
*/
Private static void display (int [] arrays ){

For (int I = 0; I <arrays. length; I ++ ){
System. out. print (arrays [I] + "");
}
}

}
In the best case, that is, when the array is already ordered, the time complexity of inserting the sort is O (n)

The more ordered the array, the less work you need to do.

In the worst case, the time complexity of the algorithm in the worst case is O (n ^ 2)
 

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.