插入排序

原理:从第二个数开始,依次与前面的进行比较(此时前面的数是有序的),找到合适的位置进行插入,比较的过程同时进行移动操作。

循环方式:
python 代码:

from random import randint
def insertion_sort():
#generate a unsorted list
origin = []
for i in xrange(0,10,1):
    origin.append(randint(1,10))
#insertion sort
print origin
for i in xrange(1,len(origin),1):
    key = origin[i]
    j = i-1
    while j >= 0 and origin[j] > key:
        origin[j+1] = origin[j]
        j -= 1
    origin[j+1] = key
print origin
if __name__ == "__main__":
insertion_sort()

java 代码:

package blog.algorithm;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class InsertionSort {
    public static void main(String args[]){
        System.out.println("begin...");
        List<Integer> origin = new ArrayList<Integer>();
        int count = 10;
        Random rd = new Random();
        while(count > 0){
            int i = rd.nextInt(100);
            origin.add(i);
            count--;
            System.out.print("" + i + "  ");
        }
        System.out.println();
        int key;
        for(int i = 0,len = origin.size(); i < len; i++){
            key = origin.get(i);
            int j = i - 1;
            for(;j >= 0 && origin.get(j) > key;j--){
                origin.set(j+1, origin.get(j));
            }
            origin.set(j+1, key);
        }
        for(int i = 0,len = origin.size(); i < len; i++){
            System.out.print("" + origin.get(i) + "  ");
        }
    }
}

递归方式(未作尾递归优化):

# -*- coding: utf-8 -*-
#!/usr/bin/env python
from random import randint

#generate a unsorted list
origin = []
def randomList():
    for i in xrange(0,10,1):
        origin.append(randint(-10,10))
    # print origin

def insert_recursion_sort(origin,begin):
    next = begin + 1
    while begin > 0:
        if origin[begin -1] > origin[begin]:
            origin[begin -1] = origin[begin] + origin[begin -1]
            origin[begin] = origin[begin-1] - origin[begin]
            origin[begin-1] = origin[begin-1] - origin[begin]
        begin -= 1
    if next < len(origin):
        insert_recursion_sort(origin, next)

def merge_sort(origin,begin,end):
    if begin < end:
        middle = (end + begin)/2
        merge_sort(origin, begin, middle)
        merge_sort(origin, middle + 1, end)
        merge(origin, begin, middle, end)

if __name__ == '__main__':
    randomList()
    print origin
    insert_recursion_sort(origin, 1)
    print origin

jke_zq
50 声望2 粉丝

引用和评论

0 条评论