C语言-选择排序

1.选择排序

  • 选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理如下。首先在未排序序列中找到最小元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小元 素,然后放到排序序列末尾。以此类推,直到所有元素均排序完毕。

2.选择排序的基本思想

  • 第一趟排序在所有待排序的n个记录中选出关键字最小的记录,将它与数据表中的第一个记录交换位置,使关键字最小的记录处于数据表的最前端;第二趟在剩下的n-1个记录中再选出关键字最 小的记录,将其与数据表中的第二个记录交换位置,使关键字次小的记录处于数据表的第二个位置;重复这样的操作,依次选出数据表中关键字第三小、第四小...的元素,将它们分别换到数据表的第三、第四...个位置上。排序共进行n-1趟,最终可实现数据表的升序排列。

    
#include <stdio.h>

int main(int argc, const char * argv[]) {
    // 已知一个无序的数组, 里面有5个元素, 要求对数组进行排序
    int nums[8] = {99, 12, 88, 34, 5, 44, 12, 100};
    int length = sizeof(nums) / sizeof(nums[0]);
    printf("length = %i
", length);
    for (int i = 0; i < length; i++) {
        printf("nums[%i] = %i
", i, nums[i]);
    }
    
    // length - 1是为了防止角标越界
    // length - 1因为最后一个元素已经没有可以比较的了
   
    for (int i = 0; i < length - 1; i++) {
        for (int j = i+1; j < length; j++) {

       // 交换位置
            if (nums[i] > nums[j]) {
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
            }
        }
    }
    
    printf("--------------
");
    for (int i = 0; i < length; i++) {
        printf("nums[%i] = %i
", i, nums[i]);
    }
    
    return 0;
}
原文地址:https://www.cnblogs.com/wlios/p/4596588.html