/********************************************************************** * 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