Select Sort 的理解

2016-01-25  本文已影响0人  HeskeyBaozi

Explain with a pic

选择排序.jpg

Pseudo-Code

WHILE UnsortedSize > 0
    FIND the smallest value in the unsorted set AS the MIN 
    // 在未排序的集合中,按顺序查找一个最小值

    SWAP the MIN and the First element of the unsorted set 
    // 将这个最小值和未排序第一个元素交换

    UnsortedSize decrease // 未排序集合减少一个元素
END WHILE

Example

The Size of the array is ZERO?

数组大小为零的情况.jpg

The Size of the array is ONE?

数组大小为1的情况.png

General Condition?

一般情况.jpg

C code

void SelectSort(int arr[], const int arrsize){
    if(arrsize == 0) return;
    for(int UnsortedSize = arrsize; UnsortedSize > 0; UnsortedSize--){
        int Unsorted_Left = arrsize - UnsortedSize; // 未排序集合左边界(包含)
        int Unsorted_Right = arrsize - 1; // 未排序集合右边界(包含)
        int MIN = Unsorted_Left; // 假定从左边界开始寻找最小值
        for(int i = Unsorted_Left; i <= Unsorted_Right; i++){
            if(arr[i] < arr[MIN]){
                MIN = i;
            }
        } // 实际上,MIN只是一个下标
        int temp = arr[Unsorted_Left];
        arr[Unsorted_Left] = arr[MIN];
        arr[MIN] = temp;
        // 将值最小的元素和未排序集合最左元素交换
    }
    return;
}
上一篇下一篇

猜你喜欢

热点阅读