1. Introduction
Select sort works by selecting the smallest (or largest) element of the data element to be sorted each time, and storing it at the beginning of the sequence until all the data elements to be sorted are exhausted. Select Sort is an unstable sort method. The selection sort is sort of similar to the bubbling sort. Unlike the bubbling Sort interchange data, the selection sort only occurs after the smallest data has been determined. How to exchange it? We can use the following set of data as a test:
2, 1, 5, 4, 9 第一次排序:1, 2, 5, 4, 9 第二次排序: 1, 2, 5, 4, 9 第三次排序: 1, 2, 4, 5, 9 第四次排序: 1, 2, 4, 5, 9
2. Algorithm idea
So from the sort steps above you can see that the selection sort should look like this:
(1) Every time you sort, you need to find the nth small data and exchange it with array[n-1].
(2) Wait until n data are sorted, then select Sort End.
3. Code
void Select_sort (int Array[],intLength) {intInner, outer, index,value, median;if(NULL = =Array||0= = length) return; for(outer =0; Outer < length-1; Outer + +) {value=Array[Outer]; index = outer; for(Inner = outer +1; Inner < length; Inner + +) {if(Array[Inner] <value){value=Array[Inner]; index = inner; } }if(Index = = outer) continue; Median =Array[index];Array[Index] =Array[Outer];Array[outer] = median; }}
4. Test code
voidPrint(intArray[],int length){int Index;if(NULL = = Array | |0==length)return; for(Index=0;Index<length;Index++)printf("%d", array[Index]);} void Test () {intData[] = {2,1,5,4,9};intsize = sizeof (data)/sizeof (int); Select_sort (data, size);Print(data, size);}
5. Analysis
From the idea of choosing a sort or the code above, it is easy to see that finding the smallest element requires a looping process, and sequencing is a process that requires a loop. It is therefore obvious that the time complexity of this algorithm is also O (n*n). This means that the value in the case of N is relatively small, the algorithm can guarantee a certain speed, when n is large enough, the efficiency of the algorithm will be reduced. And with the increase of N, the time of the algorithm grows rapidly. Therefore, special attention should be paid to the use.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Algorithm Learning ranking algorithm (three) (select Sort method)