C++ bubble sort data structure algorithm and improved algorithm

  • 2020-04-01 21:41:11
  • OfStack

The program code is as follows:


//BubbleSort. CPP: defines the entry point for 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;
    a = b;
    b = t;
}
template<typename T>
void Bubble(T a[], int n)
{//Move the largest element of array a[0:n-1] to the right by 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 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 regular bubbling, whether or not the two adjacent elements are sorted, bubbling is not necessary, so let's improve on that. Design a bubble sort algorithm with timely termination:

If there is no element swap during a bubble, the array is sorted and there is no need to continue the bubble sort. The code is as follows:


//BubbleSort. CPP: defines the entry point for 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;
    a = b;
    b = t;
}
template<typename T>
bool Bubble(T a[], int n)
{//Move the largest element of array a[0:n-1] to the right by bubbling
    bool swapped = false;//Not exchanged yet
    for(int i =0 ;i < n-1; i++)
    {
        if(a[i] >a[i+1])
        {
            Swap(a[i],a[i+1]);
            swapped = true;//There was an exchange
        }
    }
    return swapped;
}
template<typename T>
void BubbleSort(T a[],int n)
{//Bubble sort 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 normal bubbling in the worst case, but reduces the number to n-1 in the best case.


Related articles: