Insert sort directly

Source: Internet
Author: User

Insert sort directly

Direct insertion sorting is a simple sorting method. The basic idea is to regard the first element of the original sequence as an ordered sequence at the beginning. Then, the second element of the original sequence and its subsequent elements are extracted in sequence, and inserted to the appropriate position in the sequence. This completes the sorting after N-1 inserts.

// Insert the sorting directly, x the array to be sorted, and n the array length is private static void sort (int [] x, int n) {int I, j, t; for (I = 1; I <n; I ++) {// I indicates the number of inserts, n-1-1 inserts t = x [I]; for (j = I-1; j> = 0; j --) {// find the location where t is to be inserted if (t <x [j]) {// if t <x [j], t is to be inserted before x [j]. x [j + 1] = x [j]; // x [j] is to be moved backward, so x [j + 1] = x [j]} else {break; // locate and exit the loop} x [j + 1] = t; // insert directly} // print the sorted array for (int m = 0; m <x. length; m ++) {System. out. println (x [m]);} return ;}




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.