插入排序

算法原理:

數組R[1...n], R[1]爲有序區, R[2...n]爲無序區。 從i=2起直至i=n止,依次尋找R[i]在當前有序區R[1...i-1]的位置並插入。


java實現:

/**
 * 插入排序,從小到大
 * 數組實現
 *
 */
public class InsertSort {


public int[] insertSort(int[] arrays){
if(null == arrays || arrays.length <= 1){
return arrays;
}
int pos = -1;
int tmp;
for(int i = 1; i< arrays.length; i++){
pos = findPosition(arrays,i);
if(pos != i){
tmp = arrays[i];
for(int j= i-1;j >= pos;j--){
arrays[j+1] = arrays[j];
}
arrays[pos] = tmp;
}
}
return arrays;
}


private int findPosition(int[] arrays, int i) {
for(int j = 0; j < i; j++){
if(arrays[i]< arrays[j]){
return j;
}
}
return i;
}

public static void main(String[] args){
int[] arrays = {10,5,4,8,74,58,12,14,14,56,3,1,11,57,41,102,13};
arrays = new InsertSort().insertSort(arrays);
for(int i = 0; i < arrays.length; i++){
System.out.print(arrays[i]);
System.out.print(",");
}
}
}



/**
 * 插入排序單鏈表實現
 * 從小到大排序
 *
 */
public class InsertSortWithLink {


public Node insertSort(Node head){
if(null == head || null == head.getNextNode()){
return head;
}
Node result = head;
Node curNode = head.getNextNode();
Node iter = head;
Node iterPreNode = null;
Node curPreNode = head;
while( curNode != null) {
iter = result;
iterPreNode = null;
while(iter != curNode){
if(curNode.getValue() < iter.getValue()) {
if( null == iterPreNode ){
curPreNode.setNextNode(curNode.getNextNode());
curNode.setNextNode(iter);
result = curNode;
} else {
iterPreNode.setNextNode(curNode);
curPreNode.setNextNode(curNode.getNextNode());
curNode.setNextNode(iter);
}
curNode = curPreNode.getNextNode();
break;
} else {
iterPreNode = iter;
iter = iter.getNextNode();
}
}
if(iter == curNode) {
curPreNode = curNode;
curNode = curPreNode.getNextNode();
}
}
return result;
}

public static void main(String[] args){
Node node1 = new Node(10);
Node node2 = new Node(5,node1);
Node node3 = new Node(8,node2);
Node node4 = new Node(19,node3);
Node node5 = new Node(28,node4);
Node node6 = new Node(12,node5);
Node node7 = new Node(19,node6);

Node node = new InsertSortWithLink().insertSort(node7);

while(node.getNextNode() != null){
System.out.print(node.getValue());
System.out.print(",");
node = node.getNextNode();
}
System.out.print(node.getValue());
}
}


發佈了31 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章