Selecting sort and bubble sort performs the same number of comparisons, with the same time complexity: O (n^2), which reduces the number of exchanges between elements in the selection sort.
Insert sort: For a set of unordered arrays, select an element in the array as a tag, the left side of the element of the tag is already ordered (the first marker is the element labeled 1), which means that the left side of the markup element is ordered, and the right side is unordered. At this point, you want to insert the tagged element into the left-hand-ordered element;
The idea of inserting an ordered element to the left is to dequeue the tagged element (into a temporary variable), then compare it to the left element, and if the comparison element is larger than the tagged element, the element being compared needs to move to the right.
The Java code is as follows:
package algorithm;
public class insertsort{
Private long[] A;
private int nelement;
Public insertsort (int max) {
a=new Long[max];
nelement=0;
}
public void Insert (long element) {
A[nelement]=element;
nelement++;
}
public void display () {
for (int j=0;j<nelement;j++) {
System.out.println (a [j]+ "");
}
}
public void Insertsort () {
for (int out=1;out< nelement;out++) {
Long temp=a[out];
int in=out;
while (in>0&&a[in-1]>temp) {
A[in]=a[in-1];
--in;
}
A[in]=temp;
}
}
}
Test code:
Package algorithm;
Import Org.junit.Before;
Import Org.junit.Test;
public class Insertsorttest {
Private Insertsort testobject=new Insertsort (20);
@Before
public void init () {
Testobject.insert (5442l);
Testobject.insert (8999l);
Testobject.insert (65l);
Testobject.insert (11189l);
Testobject.insert (12l);
Testobject.insert (20l);
Testobject.insert (1990l);
Testobject.insert (89l);
Testobject.insert (58l);
Testobject.insert (29l);
}
@Test
public void Test1 () {
Testobject.display ();
System.out.println ("before");
Testobject.insertsort ();
Testobject.display ();
System.out.println ("after");
}
}
Operation Result:
5442 8999, 11189, 1990, before
1990 5442 8999 11189 after
Common sorting Algorithms for Java implementations 2-insert Sort