algorithm chapter1

SelectSort

  选择排序的思想是假设当前元素的左侧是一个已经按升序排列的子数组(且未排序子数组中的元素都不小于该数组的最大元素),我们从当前元素开始向后寻找最小的元素并替换到当前位置,就可以不断扩大已排序子数组的范围,最终完成整个数组的排序。

  

  根据上图我们可知,要将n个元素放到对应的位置,我们需要n次循环;因为我们假设当前元素的最左端已经是升序排好的数组,而第一次选择时我们当前集合左侧实际上是一个空集合,因此我们只需要找出当前未排序集合当中最小的元素放到最左侧,就将一个元素放入了有序子数组;而从第二次开始我们基于第一次的假设和第一次的操作可知,当前未排序数组中没有任何元素是小于左侧已排序数组中的元素的,因此我们只需要同第一次一样选择最小元素放到最左侧即将又一个元素放入了有序子数组。

  我们每进行一次选择,相应的未排序子数组就减一,因此每次进行的比较是从n-1到0的递减等差数列,因此得出算法总的比较次数为n2/2(无论好坏),而每次选择完成都要进行1次交换(有可能与自身),所以交换次数为n,由此我们可以看出选择排序的复杂度并不取决于数组的输入顺序,而只取决于数组的大小。

 1 package cn.johnson.day02;
 2 
 3 import org.junit.Assert;
 4 import org.junit.Test;
 5 
 6 import cn.johnson.dependencies.StdOut;
 7 
 8 /**
 9 * 
10 * @author Johnson
11 * 
12 * Selection sort
13 * 
14 * as there would be n loops thus there would be n^2-n/2(n-1 comparasions
15 * for each loop ) comparasions and n(0/1 exchange for each loop )
16 * exchanges.
17 */
18 public class SelectionSort {
19 public static void sort(Comparable[] arr) {
20 Assert.assertNotNull(arr);
21 
22 for (int i = 0; i < arr.length - 1; i++) {// might be n loop ,n stands
23 // for the length of array.
24 
25 int min = i;// assume the first element is the minimum;
26 
27 for (int j = i + 1; j < arr.length; j++) {// in each loop, we'd find
28 // the minimum
29 // element,thus we need
30 // n-1 comparasions
31 if (arr[j].compareTo(arr[min]) < 0) {
32 min = j;
33 StdOut.print("min index " + j);
34 }
35 }
36 
37 exch(arr, min, i);
38 }
39 }
40 
41 private static void exch(Comparable[] arr, int min, int i) {
42 Comparable temp = arr[min];
43 arr[min] = arr[i];
44 arr[i] = temp;
45 }
46 
47 @Test
48 public void testQuickSort() {
49 Integer[] arr = { 2, 2, 1, 4, 2, 1 };
50 SelectionSort.sort(arr);
51 StdOut.println("array after sort ");
52 for (Integer e : arr) {
53 StdOut.print(e + " ");
54 }
55 }
56 }

 

posted @ 2013-12-31 23:30  Johnson2014  阅读(159)  评论(0)    收藏  举报