SnapTimes

News In A Snap!!

C++ Programs: Bubble Sort

April 8, 2015

C++_Main

What is Bubble Sort?

Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order.

Code


//Bubble sort

#include <iostream.h>
 #include<conio.h>

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 display(int array[], int n) {
 for (int i=0; i<n; i++) {
 cout << array[i] << " ";
 }
 cout << endl;
 }

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]);
 }
 cout << "Pass " << i+1 << ": ";
 display(table, n);
 }
 }

int quantity;
 int* tab;

int main() {
 clrscr();
 cout << "How many numbers? ";
 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: ";
 display(tab, quantity);
 cout << endl;
 sort(tab, quantity);
 cout << "\nAfter sorting: ";
 display(tab, quantity);
 cout << endl;

getch();
 return 0;
 }

Output:

bs


SnapTimes.in | Get Tech Addicted...
About Us | Contact Us | ©2017