Saturday, May 2, 2015

Bubble Sort in Descending Order Using Pointers in C++

In this article I would like to share with you a bubble sort program that I wrote in C++ that uses pointers as its data structure. What does our program will do is to as the user how many numbers to be sorted using Bubble Sort sorting algorithm. It will display the original arrangement of numbers and after which it will display the sorted numbers in descending order.


If you like my work please send me an email at jakerpomperada@gmail.com and jakerpomperada@yahoo.com.

People here in the Philippines who wish to contact me can call and text me in this number 09173084360.

Thank you very much and God Bless.




Sample Program Output


Program Listing


#include <cstdlib>
#include <iostream>

using namespace std;

int compare(int, int);
void sort(int[], const int);
void swap(int *, int *);

int compare(int x, int y)
{
     return(x < y);
}

void swap(int *x, int *y)
{
     int temp;
     temp = *x;
     *x = *y;
     *y = temp;
}

void sort(int table[], const int n)
{
     for(int i = 0; i < n; i++)
     {
          for(int j = 0; j < n-1; j++)
          {
               if(compare(table[j], table[j+1]))
                    swap(&table[j], &table[j+1]);
          }
     }
}

int quantity;
int* tab;

int main(int argc, char *argv[])
{
    cout << "\t\tBUBBLE SORT IN DESCENDING ORDER USING POINTERS";
    cout << "\n\n\t\t Created By: Mr. Jake R. Pomperada, MAED-IT";
    cout << "\n\n";   
    cout << "How Many Items :=> ";
cin >> quantity;
tab = new int [quantity];
cout << "Input numbers: \n\n";
for (int i = 0; i < quantity; i++)
{
    int x = i;
    cout << "#" << ++x << ": ";
    cin >> tab[i];
}

cout << "\nBefore sorting: ";
for (int i = 0; i < quantity; i++)
{
     cout << tab[i] << " ";
}

cout << "\nAfter sorting: ";
sort(tab, quantity);
for(int i = 0; i < quantity; i++)
{
     cout << tab[i] << " ";
}
 cout << "\n\n";
    system("PAUSE");
    return EXIT_SUCCESS;
}












No comments:

Post a Comment