Pseudo Code for Bubble Sort Algorithm
Procedure BubbleSort(A1, ... , An : real numbers with n >= 2)
for i := 1 to n - 1
for j := 1 to n - 1
if Aj > Aj+1 then exchange Aj and Aj+1
{A1, .... An is in increasing order}
C Plus Plus Program For Bubble Sort Algorithm
#include <iostream>
using namespace std;
// Gurpreet Singh
// Bubble Sort Program
// Function Prototypes
const int ARRAY_SIZE = 5;
void printlist( int list[], int ARRAY_SIZE);
void bubblesort ( int list[], int ARRAY_SIZE);
void sortlist( int list[], int ARRAY_SIZE);
int main()
{
int list[ARRAY_SIZE] = { 5,4,3,2,1 };
cout << "The Unsorted List: ";
printlist(list,ARRAY_SIZE); // Function Call
cout<<endl;
cout<<"Bubble Sort";
cout<<endl;
bubblesort(list,ARRAY_SIZE);
system("pause");
return 0;
}
// printlist PRINTS THE ARRAY
void printlist (int list[], int ARRAY_SIZE)
{
for(int i = 0; i < ARRAY_SIZE; i++)
cout<<list[i]<<" ";
cout<<endl;
}
// sortlist Sorts the ARRAY
void sortlist (int list[], int ARRAY_SIZE)
{
int swap;
// int list[ARRAY_SIZE] = { 21, 13, 17, 5, 3 };
for(int i = 0; i < ARRAY_SIZE; i++)
{
if (i <= 3) // the compiler compares four elements
{
if(list[i] > list [i+1])
{
swap = list[i+1];
list[i+1] = list[i];
list[i] = swap;
}
}
printlist(list, ARRAY_SIZE);
}
cout<<endl;
}
void bubblesort ( int list[], int ARRAY_SIZE)
{
for (int i = ARRAY_SIZE - 1; i > 0; i--)
{
sortlist(list, ARRAY_SIZE);
}
}
No comments:
Post a Comment