Bubble Sorting is a simple sort. In this sort, the "Bubble Policy" is used to move the maximum element to the rightmost. During the bubble process, two adjacent elements are compared. If the left side is greater than the right side, two elements are exchanged. After such a bubble, you can ensure that the maximum is on the rightmost side. Then, execute n bubbles and then sort them.
The program code is as follows:
// BubbleSort. cpp: defines the entry point of the console application.
//
# Include "stdafx. h"
# Include <cmath>
# Include <iostream>
Using namespace std;
# Define MAXNUM 20
Template <typename T>
Void Swap (T & a, T & B)
{
Int t =;
A = B;
B = t;
}
Template <typename T>
Void Bubble (T a [], int n)
{// Move the largest element in array a [0: n-1] To the right through bubbling
For (int I = 0; I <n-1; I ++)
{
If (a [I]> a [I + 1])
Swap (a [I], a [I + 1]);
}
}
Template <typename T>
Void BubbleSort (T a [], int n)
{// Bubble sort the n elements in array a [0: n-1]
For (int I = n; I> 1; I --)
Bubble (a, I );
}
Int _ tmain (int argc, _ TCHAR * argv [])
{
Int a [MAXNUM];
For (int I = 0; I <MAXNUM; I ++)
{
A [I] = rand () % (MAXNUM * 5 );
}
For (int I = 0; I <MAXNUM; I ++)
Cout <a [I] <"";
Cout <endl;
BubbleSort (a, MAXNUM );
Cout <"After BubbleSort:" <endl;
For (int I = 0; I <MAXNUM; I ++)
Cout <a [I] <"";
Cin. get ();
Return 0;
} But the regular bubbles, whether or not the adjacent two elements have already sorted out the order, need to bubble, which is unnecessary, and we can improve this. Design a timely terminated Bubble Sorting Algorithm:
If element swapping does not occur during a bubble process, it indicates that the array has been sorted in order and there is no need to continue the Bubble sorting. The Code is as follows:
// BubbleSort. cpp: defines the entry point of the console application.
//
# Include "stdafx. h"
# Include <cmath>
# Include <iostream>
Using namespace std;
# Define MAXNUM 20
Template <typename T>
Void Swap (T & a, T & B)
{
Int t =;
A = B;
B = t;
}
Template <typename T>
Bool Bubble (T a [], int n)
{// Move the largest element in array a [0: n-1] To the right through bubbling
Bool swapped = false; // exchange has not occurred
For (int I = 0; I <n-1; I ++)
{
If (a [I]> a [I + 1])
{
Swap (a [I], a [I + 1]);
Swapped = true; // exchange occurred
}
}
Return swapped;
}
Template <typename T>
Void BubbleSort (T a [], int n)
{// Bubble sort the n elements in array a [0: n-1]
For (int I = n; I> 1 & Bubble (a, I); I --);
}
Int _ tmain (int argc, _ TCHAR * argv [])
{
Int a [MAXNUM];
For (int I = 0; I <MAXNUM; I ++)
{
A [I] = rand () % (MAXNUM * 5 );
}
For (int I = 0; I <MAXNUM; I ++)
Cout <a [I] <"";
Cout <endl;
BubbleSort (a, MAXNUM );
Cout <"After BubbleSort:" <endl;
For (int I = 0; I <MAXNUM; I ++)
Cout <a [I] <"";
Cin. get ();
Return 0