Subscribe to Invariance_Under_Translation        RSS Feed
-----

Bubble Sort Algorithm

Icon Leave Comment
I thought that as an extension of my arrays tutorial i would throw in an example of the Bubble Sort Algorithm. This is a simple, quick way to sort a set of numbers into ascending or descending order.

#include<iostream>
 
using namespace std;
 
int main()  {
 
int array1[] = {10,8,3,7,22};  //Creating an array of five variables
int i = 0;
cout<<"Unsorted array: ";
for(i; i < 5; i++) {
cout<<array1[i]<<", ";
}
cout<<endl;
cout<<endl;
 
int temp;
for (int m = 0; m < 5; m++) {
   for (int n = 0; n < m; n++) {				  //So that we can loop through the array five times.
	 if (array1[n] > array1[n+1])  {	//We are sorting in ascending order, so if the first variable is greater
	 temp = array1[n];					  //than the second the if statement will execute. 
	 array1[n] = array1[n+1];		   //We assign the first variable to a temporary variable,
	 array1[n+1] = temp;				 //and then swap the second variable to the first position.
	 }											   //We then assign the second position with the temporary variable, and we're done!
	}
   }
cout<<"Sorted array: ";
int j = 0;
for(j = 0; j < 5; j++) { 
cout<<array1[j]<<", ";
 }
cout<<endl;
cin.get();
}


0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

July 2018

S M T W T F S
1234567
891011121314
15161718 19 2021
22232425262728
293031    

Tags

Recent Entries

Recent Comments

Search My Blog

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)