首页 > 编程语言 > 详细

三、直接插入排序

时间:2018-10-05 00:33:13      阅读:197      评论:0      收藏:0      [点我收藏+]

1、Java语言实现

抽象类

public abstract class Sorter {
    public abstract void sort(int [] array);
}

实现类

public class StraightInsertionSorter extends Sorter {

    @Override
    public void sort(int[] array) {
        for (int i = 1; i < array.length; i++) {
            int temp = array[i];
            if (array[i] < array[i - 1]) {
                int j = i - 1;
                while (j >= 0 && temp < array[j]) {
                    array[j + 1] = array[j];
                    j--;
                }
                array[j + 1] = temp;
            }
        }

    }

}

测试

public class Test {
    public static void main(String[] args) {
        int[] arr = {94, 12, 34, 76, 26, 9, 0, 37, 55, 76, 37, 5, 68, 83, 90, 37, 12, 65, 76, 49};
        //int[] arr = {5, 2, 0, 1, 3, 4};
        Sorter sorter = new StraightInsertionSorter();
        sorter.sort(arr);

        System.out.println(Arrays.toString(arr));

    }
}

2、python语言实现

from abc import ABCMeta, abstractmethod


class Sorter:
    __metaclass__ = ABCMeta

    @abstractmethod
    def sort(self, array):
        pass


# 第一种写法
# class StraightInsertionSorter(Sorter):
#     def sort(self,array):
#         i = 1
#         length = len(array)
#         while i < length:
#             temp = array[i]
#             if array[i] < array[i - 1]:
#                 j = i - 1
#                 while j >= 0 and temp < array[j]:
#                     array[j + 1] = array[j]
#                     j -= 1
#                 array[j + 1] = temp
#             i += 1

# 第二种写法
class StraightInsertionSorter(Sorter):
    def sort(self, array):
        i = 0
        length = len(array)
        while i < length - 1:
            k = i
            j = i
            while j < length:
                if array[j] < array[k]:
                    k = j
                j = j + 1
            if k != i:
                array[k], array[i] = array[i], array[k]
            i = i + 1


if __name__ == __main__:
    arr = [5, 4, 2, 1, 3, 0, 6]
    print(arr)
    straightInsertionSorter = StraightInsertionSorter()
    straightInsertionSorter.sort(arr)
    print(arr)

 

三、直接插入排序

原文:https://www.cnblogs.com/beanbag/p/9743803.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!