三、直接插入排序

本文详细介绍了直插排序算法在Java和Python中的实现方式。在Java中,通过定义抽象类Sorter并创建StraightInsertionSorter类来实现排序功能;在Python中,则使用ABC元类和abstractmethod装饰器来定义抽象基类Sorter。两种实现均提供了完整的代码示例,并通过实例验证了排序算法的有效性。

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


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值