Sorting algorithm (ii)

Source: Internet
Author: User

1. Insert sort-Direct insert sort (straight insertion sort)

Basic idea:

    Insert a record into an ordered table that is already sorted, resulting in an ordered table with a new, 1 record count. That is, the first record of the sequence is considered to be an ordered subsequence, and then inserted from the second record one after the other until the entire sequence is ordered.

    Important: set up Sentinel as a temporary storage and judgment array boundary.

Example of a direct insert sort:

If you encounter an element equal to the insert, the insertion element places the element you want to insert behind the equal element. So, the order of the equal elements is not changed, the order from the original unordered sequence is the order of the sequence, so the insertion sort is stable.

The implementation of the algorithm:

      

 Packagesort; Public classInsertsort { Public Static voidMain (string[] args) {intA[] = {12,42,32,23,56,35,76,36,2}; Insertsort.sort (A,8);  for(inti=0;i<a.length; i++) {System.out.print (A[i]+" "); }    }         Public Static voidSortint[] arr,intN) {             for(intI=1; i<n; i++){                    if(Arr[i] < arr[i-1]) {//if the first element is greater than the i-1 element, it is inserted directly. Otherwise, enter the ordered table to determine the insertion position after inserting                                intj = i-1;//is already the length of the row ordinal array                intx = Arr[i];//set Sentinel to store elements with sortingArr[i]= Arr[i-1];//Move backward One                                 while(X <Arr[j]) {Arr[j+1] = Arr[j];//Move backward Onej--; } arr[j+1] = x;//Insert to the correct location            }        }    }}

Efficiency:

  Complexity of Time: O (n²)

The other insert sort has two-insert sort, 2-way insert sort.

Sorting algorithm (ii)

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.