美文网首页web前端学习C语言开源时代
排序算法——选择排序(selection sort)

排序算法——选择排序(selection sort)

作者: NiceBlueChai | 来源:发表于2017-10-11 12:49 被阅读52次

    选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。 选择排序是不稳定的排序方法(比如序列[5, 5, 3]第一次就将第一个[5]与[3]交换,导致第一个5挪动到第二个5后面)。
    性质:不稳定的排序方法


    示例代码:

    #include <stdio.h>
    
    void select_sort(int a[], int n)
    {
        for(int i=0; i < n-1; i++)
        {
            int pos = i;
            for(int j=i+1; j<n; j++)
            {
                // 找到最小值的那个元素的下标
                if(a[j] < a[pos])
                {
                    pos = j;
                }
            }
            // 把最小值调换到最前面
            if(pos != i)
            {
                int temp = a[pos];
                a[pos] = a[i];
                a[i] = temp;
            }
        }
    }
    
    int main()
    {
        int a[5] = { 6, 8, 7, 4, 5};
        int n = 5;
        
        int b[4] = { 1, 9, 2, 6};
        select_sort(b, 4);
        return 0;
    }
    
    
    
    • 用户自定义类型的排序

    #include <stdio.h>
    #include <string.h>
    
    struct Student
    {
        int id;
        char name[32];
    };
    
    void select_sort(Student a[], int n) // 1: 参数类型
    {
        for(int i=0; i < n-1; i++)
        {
            int pos = i;
            for(int j=i+1; j<n; j++)
            {
                // 找到最小值的那个元素的下标
                //if(a[j].id < a[pos].id) // 3. 比较大小的方法
                if( strcmp (a[j].name ,a[pos].name) < 0)
                {
                    pos = j;
                }
            }
            // 把最小值调换到最前面
            if(pos != i)
            {
                Student temp = a[pos]; // 2. 元素类型
                a[pos] = a[i];
                a[i] = temp;
            }
        }
    }
    
    int main()
    {
        Student a[4];
        a[0].id = 4;
        strcpy(a[0].name, "shaofa");
    
        a[1].id = 7;
        strcpy(a[1].name, "anxin");
    
        a[2].id = 2;
        strcpy(a[2].name, "jennifer");
    
        a[3].id = 5;
        strcpy(a[3].name, "other");
    
        select_sort(a, 4);
        return 0;
    }
    

    1.时间复杂度

    相关文章

      网友评论

        本文标题:排序算法——选择排序(selection sort)

        本文链接:https://www.haomeiwen.com/subject/kkbiyxtx.html