Search This Blog

Tuesday, 12 June 2018

CS201 Introduction to Programming - bubble sorting by using swap fuction

// This program uses bubble sorting to sort a given array.
// We use swap function to interchange the values by using pointers

#include <iostream>

using namespace std; //Allows computer to output data

/* Prototye of function swap used to swap two values */ 
void swap(int *, int *);

main() //main function begins
{
int x[] = {1,3,5,7,9,2,4,6,8,10};
int i,j,swaps;

for (i=0;i<=10;i++)
{
swaps=0;
for (j=0;j<=10;j++)
{
// compare two values and interchange if needed
if (x[j]>x[j+1])
{
swaps++;
swap(&x[j],&x[j+1]);
}
}
}
//display the array’s elements after each comparison
for (j=0;j<=10;j++)
{
cout << x[j] << "\t\n";
if (swaps==0)
break;
}

}//end of main function


//function using pointers to interchange the values
void swap(int *a, int *b)
{
int tmp;
if (*a > *b)
{
tmp=*a;
*a=*b;
*b=tmp;
}
//cout << *a;
//cout << *b;
}

No comments:

Post a Comment