1、Java语言实现
抽象类
public abstract class Sorter {
public abstract void sort(int [] array);
}
实现类
/**
* @author BEAN_BAG
* @date 2018年10月8日 14:41:53
* 直接选择排序
*/
public class StraightSelectionSorter extends Sorter {
@Override
public void sort(int[] array) {
int temp;
//i从第一个元素遍历到倒数第二个元素
for (int i = 0; i < array.length - 1; i++) {
int k = i;
//j从i的下一个元素遍历到最后一个元素
//此for循环用于找到右侧无序区中最小的元素
for (int j = i + 1; j < array.length; j++) {
if (array[k] > array[j]) {
k = j;
}
}
if (k != i) {
//交换k和i上面的值
temp = array[k];
array[k] = array[i];
array[i] = 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};
Sorter sorter = new StraightSelectionSorter();
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 StraightSelectionSorter(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 += 1
#交换k和i的值
if k != i:
array[k],array[i] = array[i],array[k]
i += 1
if __name__ == '__main__':
arr = [5, 4, 2, 1, 3, 0, 6]
print(arr)
straightSelectionSorter = StraightSelectionSorter()
straightSelectionSorter.sort(arr)
print(arr)