Original: Step by step Write algorithm (select sort)
"Disclaimer: Copyright, welcome reprint, please do not use for commercial purposes. Contact mailbox: feixiaoxing @163.com "
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
First time sorted by: 1, 2, 5, 4, 9
Second order: 1, 2, 5, 4, 9
Third Order: 1, 2, 4, 5, 9
Fourth time sorted by: 1, 2, 4, 5, 9
a) algorithm steps
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.
B) Sort code
void Select_sort (int array[], int length) {int inner, outer, index, value, median;if (NULL = = Array | | 0 = = length) return;fo R (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; ind ex++) printf ("%d", Array[index]);} void Test () {int data[] = {2, 1, 5, 4, 9};int size = sizeof (data)/sizeof (int), Select_sort (data, size);p rint (data, size);}
Summary:
1) In fact, many methods of testing, printing is a good way, but only for the test case less than the case
2) The algorithm can be verified on the draft paper first, and then start programming
One-step-one-step write algorithm (select sort)