Three ways to implement bubble sort _c language

Source: Internet
Author: User

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.

Related Article

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.