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