Bubble sort is a basic sorting algorithm, the basic idea is to compare the size of adjacent two numbers, according to ascending or descending need to exchange, after completing a trip, the largest or smallest number will be swapped to the last line, because the last number is already the largest or smallest number so no longer compare, In the next trip to the comparison, until all the numbers are orderly.
Code:
void Bubblesort1 (A[],n)
{
int i,j,temp:
for (i=0;i<n;i++)
for (j=1;j<n-i;j++)
if (A[j-1]>a[j])//The front is greater than the following to exchange, the description is ascending sort
{
TEMP=A[J-1];
A[J-1]=A[J];
A[j]=temp;
}
}
The above is the basic bubble sorting algorithm, you can also optimize it, set a flag flag, if there is no exchange, indicating that the sort has been completed, change the value of flag
Code:
void Bubblesort2 (A[],n)
{
int i,j;
BOOL Flag=true;
while (flag)
{
Flag=false;
for (i=1;i<n;i++)
if (A[i-1]>a[i])
{
Swap (a[i-1],a[i]);
Flag=true;
}
n--;
}
}
The above optimization is to optimize the number of extra trips, there are other optimization methods, such as the number after a row of numbers are ordered, just need to sort the preceding numbers, you can record the first change of position, the number behind is orderly nature will not exchange, Then just sort the numbers from the beginning to the location, and then, after that, each time the record changes the position of the previous number is sorted, knowing that the position of the change becomes the first number indicating that the sort has been completed.
Code:
void Bubblesort3 (A[],n)
{
int i,f,k;
K=n;
while (k>0)
{
F=k;
k=0;
for (i=1;i<f;i++)
if (A[i-1]>a[i])
{
Swap (a[i-1],a[i]);
K=i;
}
}
}
Bubble sorting is an inefficient algorithm that can be used when data is low, preferably using a different sorting algorithm when the data is many.
Reference: http://blog.csdn.net/morewindows/article/details/6657829
The bubble sort of algorithm analysis