1.选择排序

2018-02-24  本文已影响0人  村上果树

选择排序算法描述:

repeat (numOfElements - 1) times

  set the first unsorted element as the minimum

  for each of the unsorted elements

    if element < currentMinimum

      set element as new minimum

  swap minimum with first unsorted position

文字描述:一个元素个数为n的数组,循环n-1次,在循环中,将未排序元素的第一个元素(为选定的元素)作为最小值,然后对这个元素其后的每一个元素进行遍历,若某一元素小于那个最小值,则将这一元素设置为最小值(也就是找出在选定元素之后,且小于选定元素的那一个元素),最后将最小值和选定的元素交换.

void selectionSort(int arr[], int n){

    for(int i = 0 ; i < n-1 ; i ++){
        // 寻找[i, n)区间里的最小值
        int minIndex = i;
        for( int j = i + 1 ; j < n ; j ++ )
            if( arr[j] < arr[minIndex] )
                minIndex = j;
        swap( arr[i] , arr[minIndex] );
    }
}

说白了,选择排序就两步,遍历和找最小值
从i = 0遍历到i = n-2,然后找[i,n)这个区间的最小值,把这个最小值放到i的位置然后进行下一趟迭代.

上一篇 下一篇

猜你喜欢

热点阅读