Introduction to sorting algorithms-Bubble Sorting Optimization

Source: Internet
Author: User

Let's talk about where Bubble Sorting needs to be optimized: based on the content of the previous article, we can know that the core of Bubble Sorting is the exchange of two-to-two comparisons. If there is an unordered sequence (,) according to the code in the previous article, operations after the first round-robin switching can be said to be unnecessary. Therefore, these operations are what we need to optimize. So how to optimize it? From observation, we can see that the main reason for unnecessary operations is that the order of the last eight numbers is already in order. Therefore, we can set a variable to mark whether the number in the sequence has sorted the code before the end of the Loop: [cpp] # include <stdio. h> void swap (int * a, int * B); int main () {int array [10] = {2, 1, 3, 4, 5, 6, 7, 8, 9, 10}; int I, j; int flag = 1; // set the flag variable for (I = 0; I <10 & flag; I ++) {flag = 0; // as long as the flag value is 0 during the next External Loop condition detection, the Order has been sorted and you do not need to continue the loop for (j = 9; j> I; j --) {if (array [j] <array [J-1]) {swap (& array [j], & array [J-1]); flag = 1; // if there is an exchange, the variable marked as 1 }}for (I = 0; I <10; I ++) {printf ("% d \ n ", array [I]);} return 0;} void swap (int * a, int * B) {int temp; temp = * a; * a = * B; * B = temp;} according to the optimized code, the time complexity of Bubble Sorting is O (n

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.