Algorithm entry-level insertion sorting

Source: Internet
Author: User

During the Chinese New Year, I read this introduction to algorithms, which has benefited a lot. This is also implemented in java based on the algorithms involved in the introduction to algorithms.

In the first article, we started from sorting. The principle of insertion sorting is very simple, just like when we were playing cards. If the card in his hand is smaller than the one before him, continue to compare and know that this card is better than the card in front of him and can be inserted behind him. Of course, in the computer, we also need to move the cards we have compared to one back.

Algorithms are provided directly here. I believe many programmers feel that some programs are better understood than our natural language.

Public class Sort {public void sort (int [] s) {if (s. length <1) {return;} for (int I = 1; I <s. length; I ++) {int key = s [I]; int j = I-1; while (j> = 0 & s [j]> key) {s [j + 1] = s [j]; j --;} s [j + 1] = key;} public static void main (String [] args) {Sort s = new Sort (); int [] st = new int [] {,}; s. sort (st); for (int I = 0; I <st. length; I ++) {System. out. println (st [I]) ;}}
The time complexity is o (n * n), which is the original address (constant element space is required at any time to store data, and merging and sorting is not the original address)

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.