The basic sorting algorithm--bubble sort

Source: Internet
Author: User

/********************************************************************** * Copyright (c) 2015,wk Studios* Filename: * C ompiler:gcc,vs,vc6.0 Win32 * AUTHOR:WK * time:2015 4 18************************************************************** /#include <stdio.h> #include <assert.h>void bubbleSort1 (int *a, int len) {for (int i=0;i<len;i+ +) {for (int j=0;j<len-1-i;j++) {if (a[j]>a[j+1]) {int temp=a[j];a[j]=a[j+1];a[j+1]=temp;}}}} Optimization code void BubbleSort2 (int *arrary, int len) {assert (Arrary! = NULL); int i = 0;bool tag = true;while (tag)//decrease a loop {tag = f alse;for (int j = 0; J < Len-1-i; J + +) {if (Arrary[j] > arrary[j+1]) {int tmp = arrary[j+1];arrary[j+1] = Arrary[j];ar RARY[J] = tmp; Tag = true;}} The beauty of ++i;//is to control the growth of I and J using a cyclic control condition, the worst case being i=len-1, which is when the i=len-1 enters the inner loop J will because the judgment does not execute the loop, then exits the loop i++, at which time the I=len while loop exits}} int main () {int a[]={9,8,7};//is arranged from small to large bubbleSort2 (a, sizeof (a)/sizeof (a[0]));//bubblesort2 (A, sizeof (a)/sizeof (A[0])) ; for (int i=0;i<8;i++) printf ("%d\n", A[i]); rEturn 0;} 

The basic sorting algorithm--bubble 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.