Java implements a commonly used sorting algorithm 2-insertion sort

Selection sort and bubble sort perform the same number of comparisons, the same time complexity: O(N^2), and the number of exchanges between elements is reduced in selection sort.

Insertion sort: For a set of unordered arrays, select an element in the array as a marker, and the left side of the marked element is already sorted (the first marker is the element with subscript 1), which means The left side of the marked element is already ordered, and the right side is unordered. At this time, the marked element should be inserted into the sorted element on the left;

The idea of ​​inserting into the ordered element on the left is: dequeue the marked element (store it in a temporary variable), and then compare it with the left element in turn. If the compared element is larger than the marked element, the compared element The element needs to be shifted 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;
}
}
}

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");
}
}
运行结果:

5442 8999 65 11189 12 20 1990 89 58 29 before
12 20 29 58 65 89 1990 5442 8999 11189 after

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325116796&siteId=291194637
Recommended