Selection Sort(排序详解 之 选择排序)

本文详细介绍了选择排序算法的工作原理及其实现过程。通过逐步演示如何找到数组中最小元素并将其放到正确位置来完成排序,帮助读者理解选择排序的基本概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Selection Sort

In thisArticle , Will talking about the selection sort , which is also O(n^2) timecomplex cost same with bubble sort we talked last time .

Same ,Westart with one array which need to be sorted :

5 , 1 , 9, 3, 7, 4 , 8 , 6 , 2

Point :

1.chose start position ,assign to min-value(or max-value)

2.compare min-value with each one in array ,if min-value(or max-value) is smaller (orbigger )than item , update min-value and min-index ,anyway , make min-value smallest (or max-value biggest).

3.swap the min-index with start position .

Let's start !


So what weare doing are :

1.set start position to 0

2.store first value into min-value, Set 0 to min-index

Next,Compare min-value to 1


Next ,Compare min-value to 9.


Keep comparing ......after 1st round , swap min-index with the1st one.


easy ? Now Do the 2nd round in the same way we just did .but the difference is thestart position ,1stposition is already the minimum value ,so this time we start from 2nd .

After Applying the same , We will get :



So Now ,Got it ? Let's continue doing with next few items .

Next ,


Next ,

Next,


Come on ,last 3 items .


Next ,


Finished .

Referencecode :

public List<int> SelectionSort(List<int> arr)
        {
            var sortedArr = newList<int>();
            arr.ForEach(sortedArr.Add);
            if (arr.Count < 2) return arr;
 
            for (var i = 0; i <sortedArr.Count; i++)
            {
                var minIndex = i;
                var min = sortedArr[minIndex];
                for (var j = i; j< sortedArr.Count; j++)
                {
                    if (min > sortedArr[j])
                    {
                        min = sortedArr[j];
                        minIndex = j;
                    }
 
                }
                if (i != minIndex)
                {
                    var tmp = sortedArr[i];
                    sortedArr[i] =sortedArr[minIndex];
                    sortedArr[minIndex] = tmp;
                }
            }
            return sortedArr;
        }
 


Thanks for reading . :)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值