[Disclaimer: All Rights Reserved. You are welcome to reprint it. Do not use it for commercial purposes. Contact Email: feixiaoxing @ 163.com]
The selected sorting is similar to the Bubble sorting. What is different from the data associated with the bubble sort exchange is that the selection of the sort will only take place after the minimum data is determined. How to exchange? We can test a set of data as follows:
2, 1, 5, 4, 9
First sorting: 1, 2, 5, 4, 9
Second sorting: 1, 2, 5, 4, 9
Third sorting: 1, 2, 4, 5, 9
Fourth sorting: 1, 2, 4, 5, 9
A) algorithm steps
From the preceding sorting steps, we can see that the selected sorting should be like this:
(1) Every time you sort data, you need to find the nth small data and exchange it with array [n-1 ].
(2) When n data items are sorted, the sorting is finished.
B) sorting code
Void select_sort (int array [], int length)
{
Int inner, 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;
}
}
Void select_sort (int array [], int length)
{
Int inner, 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;
}
}
C) Test Cases
Void print (int array [], int length)
{
Int index;
If (NULL = array | 0 = length)
Return;
For (index = 0; index <length; index ++)
Printf ("% d", array [index]);
}
Void test ()
{
Int data [] = {2, 1, 5, 4, 9 };
Int size = sizeof (data)/sizeof (int );
Select_sort (data, size );
Print (data, size );
}
Void print (int array [], int length)
{
Int index;
If (NULL = array | 0 = length)
Return;
For (index = 0; index <length; index ++)
Printf ("% d", array [index]);
}
Void test ()
{
Int data [] = {2, 1, 5, 4, 9 };
Int size = sizeof (data)/sizeof (int );
Select_sort (data, size );
Print (data, size );
}
Summary:
1) In fact, there are many testing methods. Printing is a good method, but it is only suitable for scenarios with few test cases.
2) the algorithm can be verified on the draft and then programmed.