The program code is as follows:
Copy Code code as follows:
BubbleSort.cpp: Defines the entry point for a 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;
A = b;
b = t;
}
Template<typename t>
void Bubble (T a[], int n)
{///move the largest element in the array a[0:n-1] through bubbling to the right
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 of 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 usual bubbling, whether or not the next two elements have been sorted out, is bubbling, which is not necessary, all of us to improve this. Design a timely termination bubble sort algorithm:
If an element interchange does not occur during a bubbling process, the array is sorted in order and there is no need to continue the bubble sort. The code is as follows:
Copy Code code as follows:
BubbleSort.cpp: Defines the entry point for a 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;
A = b;
b = t;
}
Template<typename t>
BOOL Bubble (T a[], int n)
{///move the largest element in the array a[0:n-1] through bubbling to the right
BOOL swapped = false;//Exchange not yet occurred
for (int i =0; i < n-1; i++)
{
if (A[i] >a[i+1])
{
Swap (a[i],a[i+1]);
swapped = true;//An exchange occurred
}
}
return swapped;
}
Template<typename t>
void Bubblesort (T a[],int N)
Bubble sort of 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, in the worst case, performs the same number of comparisons as regular bubbling, but in the best case the number of times is reduced to n-1.