排序算法-选择与插入排序

来源:互联网 发布:js选择器innerhtml 编辑:程序博客网 时间:2024/06/06 00:37

今天主要复习下选择排序以及插入排序:

1.选择排序:(百度百科的定义)每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。 选择排序是不稳定的排序方法。个人的理解:选择排序就是选择最小的数据放在前面,也是我们最直观的排序方式,举例如下{49,38,65,97,5}:

选择最小的数据5,排在最前面,交换位置{5,38,65,97,49}再重复以上的步骤直到全部完成,代码如下:

public static int[] Select(int[] input) {        for (int i = 0; i < input.length; i++) {            int min = i;            for (int j = i + 1; j < input.length; j++) {                if (input[min] > input[j]) {                    min = j;                }            }            if (min != i) {                int temp = input[i];                input[i] = input[min];                input[min] = temp;            }        }        return input;    }

test:

@Test    public void testMain() throws Exception {        int a[] = {49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62, 99, 98, 54, 56, 17, 18, 23, 34, 15, 35, 25, 53, 51};        assertArrayEquals(AlgorithmRevise.Select(a),new int[]{4,5,12,13,15,17,18,23,25,27,34,34,35,38,49,49,51,53,54,56,62,64,65,76,78,97,98,99});    }

2.插入排序:顾名思义,插入到前后大小适合的位置,不过需要注意的是,我们插入的列表一定是一个已排序的列表。举例如下{49,38,65,97,5}:

1.从第二个开始,38比49小,排在49前面

2.65比49大,不做排序

3.97也是如此

4.5与97比较,换个位置,依次比较,如果大,结束。代码如下:

//Insert algorithm    public static int[] Insert(int[] input) {        for (int i = 0; i < input.length - 1; i++) {            for (int j = i + 1; j > 0; j--) {                if (input[j] > input[j - 1]) {                    break;                } else {                    int temp = input[j - 1];                    input[j - 1] = input[j];                    input[j] = temp;                }            }        }        return input;    }

test:

@Test    public void testMain() throws Exception {        int a[] = {49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62, 99, 98, 54, 56, 17, 18, 23, 34, 15, 35, 25, 53, 51};        assertArrayEquals(AlgorithmRevise.Insert(a),new int[]{4,5,12,13,15,17,18,23,25,27,34,34,35,38,49,49,51,53,54,56,62,64,65,76,78,97,98,99});    }
谢谢!

0 0