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

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 !

Selection Sort(排序详解 之 选择排序)_第1张图片


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

Selection Sort(排序详解 之 选择排序)_第2张图片


Next ,Compare min-value to 9.

Selection Sort(排序详解 之 选择排序)_第3张图片


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


Selection Sort(排序详解 之 选择排序)_第4张图片

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 :

Selection Sort(排序详解 之 选择排序)_第5张图片



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

Selection Sort(排序详解 之 选择排序)_第6张图片

Next ,

Selection Sort(排序详解 之 选择排序)_第7张图片


Next ,

Selection Sort(排序详解 之 选择排序)_第8张图片

Next,

Selection Sort(排序详解 之 选择排序)_第9张图片


Come on ,last 3 items .

Selection Sort(排序详解 之 选择排序)_第10张图片


Next ,

Selection Sort(排序详解 之 选择排序)_第11张图片


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 . :)

你可能感兴趣的:(select)