The program code is as follows:
Copy codeThe 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 conventional bubble, whether or not the adjacent two elements have already sorted out the order, needs to bubble, this is unnecessary, and we will 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:
Copy codeThe 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;
}
The improved algorithm performs the same number of comparisons as conventional bubbles in the worst case, but it is best to reduce the number of comparisons to n-1.