One-step-one-step write algorithm (select sort)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.