C Plus Plus Bubble sorting
From GMpedia.org Wiki
The following is an example on bubble sorting in C++.
Contents |
[edit] C++ Example
In this example, numbers from 1 to 30 are randomly assigned to the array VAR. It takes the program 20 rounds to fix the sorting, each round is couted.
[edit] Initialization
#include <iostream>
using namespace std;
int main()
{
int VAR[]={0,11,6,18,17,2,3,1,19,25,20,16,5,26,27,9,21,4,15,28,22,24,7,30,10,29,14,23,8,12,13};
int count, TOTAL, wrong=0, tmp1, tmp2, i;
bool sorted;
count=0;
sorted=false;
TOTAL=30;
The int VAR[]=... line actually defines the following arrays:
VAR[01]=11; VAR[02]=6; VAR[03]=18; VAR[04]=17; VAR[05]=2; VAR[06]=3; VAR[07]=1; VAR[8]=19; VAR[9]=25; VAR[10]=20; VAR[11]=16; VAR[12]=5; VAR[13]=26; VAR[14]=27; VAR[15]=9; VAR[16]=21; VAR[17]=4; VAR[18]=15; VAR[19]=28; VAR[20]=22; VAR[21]=24; VAR[22]=7; VAR[23]=30; VAR[24]=10; VAR[25]=29; VAR[26]=14; VAR[27]=23; VAR[28]=8; VAR[29]=12; VAR[30]=13;
Note that we are not concerned with VAR[0].
[edit] Welcome Message
cout << "Hey!\n\n";
[edit] Show Numbers for the first time
for(i=1;i<=TOTAL;i++)
{
cout << VAR[i] << "\n";
}
cout << "\n\n\n";
[edit] Bubble Sorting
do
{
for(i=1;i<TOTAL;i++)
{
if (i<TOTAL)
{
if(VAR[i]>VAR[i+1])
{
wrong++;
tmp1=VAR[i];
tmp2=VAR[i+1];
VAR[i]=tmp2;
VAR[i+1]=tmp1;
}
}
cout << VAR[i] << "\n";
}
if (wrong==0)
{
sorted=true;
}
else
{
wrong=0;
sorted=false;
}
cout << "\nRound: " << count << "\n======\n";
count++;
}
while(sorted==false);
[edit] End Program
return 0; }

