插入排序
来源:互联网 发布:java 之父 编辑:程序博客网 时间:2024/06/08 03:31
算法原理:
数组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());
}
}
- 插入排序-【插入排序】
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- 插入排序
- jsp中点击图片在弹出层显示大图
- Android 触摸及手势操作GestureDetector
- 推送服务要选真正实现互动的
- C# 操作Word知识汇总
- [IOS]推送通知简述及开发实践
- 插入排序
- linux VFS 之七:VFS精髓总结
- 百度加速O2O闭环布局
- 块级元素与行内元素的区别
- redis 入门
- Android常见控件使用经验之——ListView
- HTTP 请求Apache错误码注释
- 大话重构
- 表单method="post"返回结果不同