Comparison between sorting and Bubble Sorting

Source: Internet
Author: User

Selection Sort)

Core Idea of the algorithm: select the record with the minimum keyword in n-I + 1 (I> = 1) for each record as the I record in the sequence

Simple selection operation: by comparing the n-I keywords, the minimum keyword record is selected from the n-I + 1 record, and exchange with the I (1 <= I <= n) records. First, let's look at the code for sorting by choice:

Int SelectSort (MergeType * L) {int min = 0; if (! L-> elem) {return-1;}/* comparison times: n-1 + N-2 + 1 + 0 = n * (n-1) /2 */for (int I = 0; I <L-> len-1; I ++) // each number {min = I; for (int j = I + 1; j <L-> len; j ++) // each number {if (L-> elem [j] <L-> elem [I]) {min = j; // swap (L-> elem [I], L-> elem [j]);} swap (L-> elem [I], l-> elem [min]);} return 0 ;}
Here, the smallest value is placed at the I-th position ~ Look at a simple instance with the smallest choice in the len-1

...for (int i=0; i
 
  L.elem[j]}}...
 

Here I! = J is used to avoid switching yourself. Here, let's take a look at the special characteristics of the for loop of the bubble algorithm.

Let's look at the time complexity: The worst case comparison times = (n-1) + (n-2) + ...... + 1 + 0 = n * (n-1)/2 = O (n ^ 2)

For (I = 0; I <= L-> len-1; I ++) // each trip {for (j = 0; j <L-> len-1-i; j ++) // each number {if (L-> elem [j + 1] <L-> elem [j]) {SWAP (L-> elem [j + 1], L-> elem [j]) ;}}
Bubble is to sink the maximum number into the lowest end in a row, while the sort is to compare each number with other, and compare the smallest or largest one, but it is also the biggest one from a trip. Is it a bit similar? We can see the comments in the for loop, but the meanings of the for loop are different.

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.