选择排序(Selection Sort)

选择排序就是在选择数组元素上做文章,关键是如何选择?选择的标准是什么?选择之后放在哪?所有这些都是选择排序的问题。

选择排序算法中,通常会有以下操作:

  • 从数组第一个元素开始。
  • 遍历整个数组,找到最小的元素。
  • 将最小的元素与数组第一个元素交换。
  • 从第二个元素开始重复上述步骤。

看一个例子:

Selection Sort

可以看到,一开始的数组是乱序的,红色的方块代表排好序的元素,蓝色的代表未排序的元素。

  • 从元素7开始,扫描后面的元素,找到最小的值。
  • 1是最小的元素,将1与7交换。
  • 从第二个元素开始,也就是4,扫描后面的元素找到最小值。
  • 将找到的最小值2与4交换位置。
  • 相似的,交换4和5。
  • 继续进行上述步骤,直到数组排序完成。

相应的算法实现:

#include<stdio.h>
 
// function to swap two integers
void swap(int *x, int *y)
{
    int temp = *x;
    *x = *y;
    *y = temp;
}
 
//defining a function to perform selection sort on array arr[] of given size
void selectionSort(int arr[], int size)
{
    int i,j;
 
    for(i=0;i<size;i++)
    {
        //a variable to store the position with minimum element
        int min_pos = i;
 
        //we need to check the remaining elements
        for(j=i+1;j<size;j++)
        {
            //compare each element and get the minimum element's position
            if(arr[j]<arr[min_pos])
            {
                min_pos = j;
            }
        }
 
        //now 'min_pos' contains the position with minimum element
        //so we swap the elements
        swap(&arr[i],&arr[min_pos]);
    }
}
 
// driver function to test the above function
int main(void)
{
    int i;
    int arr[10] = {3, 4, 7, 1, 10, 8, 2, 22, 99, 50};
 
    selectionSort(arr,10);
 
    printf("SORTED array:- ");
    for(i=0;i<10;i++)
        printf("%d ",arr[i]);
 
    return 0;
}
时间复杂度:O(n 2)

转载于:https://www.cnblogs.com/programnote/p/4724676.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值