Quick Start to sorting algorithms

Source: Internet
Author: User

After learning the bubble sort, we will find that this algorithm is constantly compared and exchanged. Although simple and straightforward, it clearly gives people a complicated feeling. Is there any better algorithm? This is of course, and it is terrible if it is not:-P this article introduces a better sorting algorithm than bubble: in simple sorting, we can see that the word "select" is probably two or two. That's right, the idea of this algorithm is: I chose to exchange the most suitable position with it, which greatly saves a lot of unnecessary exchanges. Because swap functions are frequently used in code writing, they are generally encapsulated into a function for calling. If there are many unnecessary exchange operations, this produces a lot of unnecessary function calls. You must know that function calls require stack-based Elastic stack, and the time overhead is useless. So when sorting, find the appropriate keywords for exchange, and move the corresponding keywords only once to complete the sorting and locating code: [cpp] view plaincopyprint? # Include <stdio. h> void swap (int * a, int * B); int main () {int a [10] = {51, 2, 65, 18, 14, 62, 5, 6, 7, 8}; int I, j; int min; for (I = 0; I <10; I ++) {min = I; for (j = I + 1; j <10; j ++) {if (a [min]> a [j]) {min = j ;}} if (min! = I) {swap (& a [min], & a [I]) ;}} for (I = 0; I <10; I ++) {printf ("% d \ n", a [I]);} return 0;} void swap (int * a, int * B) {int temp; temp = * a; * a = * B; * B = temp;} the time complexity of selecting the worst-case sorting is O (n²), although it is the same as bubble, however, the performance of sorting is better than that of bubble, because it significantly reduces the number of switching operations.

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.