Bubble sort is very easy to understand and implement to sort examples from small to large:
Sets the length of the array to n.
1. Compare the adjacent two data and exchange two data if the preceding data is larger than the following data.
2. After the No. 0 data of the array is traversed by a N-1 data, the largest data is "sunk" to the N-1 position of the array.
3. N=n-1, if N is not 0, repeat the preceding two steps, or the sort completes.
It's easy to write code by definition:
Copy Code code as follows:
Bubble Sort 1
void BubbleSort1 (int a[], int n)
{
int I, J;
for (i = 0; i < n; i++)
for (j = 1; j < N-i; J + +)
if (A[j-1] > A[j])
Swap (A[j-1], a[j]);
}
The following is optimized to set a flag, true if this trip occurs, or false. Obviously if there was a trip that did not occur, the description of the order was completed.
Copy Code code as follows:
//Bubble Sort 2
void BubbleSort2 (int a[], int n)
{
Int J, K;
BOOL Flag;
k = n;
Flag = true;
while (flag)
{
Flag = false;
for (j = 1; j < K; J + +)
if (A[j-1] > A[j])
{
Swap (A[j-1], a[j]);
Flag = true;
}
k--;
}
}
Further optimization is done. If you have an array of 100 numbers, only the first 10 disorder, the back 90 have been ordered and are greater than the previous 10 digits, then the initial traversal, the last place of exchange must be less than 10, and the data after this position must be ordered, record this position, The second time just walk from the array head to this position.
Copy Code code as follows:
Bubble Sort 3
void BubbleSort3 (int a[], int n)
{
Int J, K;
int flag;
Flag = N;
while (Flag > 0)
{
k = Flag;
Flag = 0;
for (j = 1; j < K; J + +)
if (A[j-1] > A[j])
{
Swap (A[j-1], a[j]);
flag = j;
}
}
}
Bubble sort is, after all, an inefficient sort method that can be used in a very small amount of data. When data size is large, it is best to use other sorting methods.