The Java implementation of the insert sort algorithm.

Source: Internet
Author: User

Package utils.sort;

/**

* Insert sort, require array to be sorted must implement comparable interface

*/

public class Insertsort implements Sortstrategy

{

/**

* Sorting obj using the Insert sort algorithm

*/

public void sort (comparable []obj)

{

if (obj = null)

{

throw new NullPointerException ("The argument can not be null!");

}

/*

* The first element in the array, the i-1 in front of it is sorted, and then inserted into the previous i-1 element

*/

int size = 1;

while (Size < obj.length)

{

Insert (obj, size++, obj[size-1]);

}

}

/**

* Insert an element in an array that is already sorted so that the inserted array remains ordered

* @param obj already sorted array

* Size of the array @param size has been sorted

* @param c elements to be inserted

*/

private void Insert (comparable []obj, int size, comparable c)

{

for (int i = 0; i < size; i++)

{

if (C.compareto (Obj[i]) < 0)

{

System.out.println (Obj[i]);

If the element to be inserted is less than the current element, then the element after the current element is moved back one

for (int j = size; j > i; j--)

{

OBJ[J] = obj[j-1];

}

Obj[i] = c;

Break

}

}

} }

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.