18)

Program 17 - The bubblesort

Program 17 The bubblesort Source code - prog17.c
This page doesn't show any new 'C' commands, but shows how a common algorithm for sorting numbers ( or anything ) into order works - the bubblesort. There is an explaination of the bubblesort algorithm below to begin with. It shows how four randomly selected playing cards are sorted into ascending order using the algorithm.

This isn't the only sorting algorithm, there are quite a few of them, but it is quite a simple one to understand to being with. After the explanation of the bubblesort, it has been implemented into a function in the lottery number selector program, so that the numbers are displayed in sorted ascending order.

 

The bubblesort algorithm explained
The bubblesort algorithm is a common algorithm used to sort things into an order. These can be numbers, words, or even cards, in fact anything that can be sorted. The explanation below uses cards to demonstrate the bubblesort in action. You can do this manually using a pack of cards. The following will be large to explain and will probably seem like it takes forever to get the four cards sorted into order, but in computer speed terms it is fractions of a second.

Initially four cards ( or more if you prefer ) are dealt from a shuffled deck and placed in order, the aim is to get these cards into ascending order ( lowest to highest - aces low )

1 2 3 4

The first step is to compare the cards in position 1 and 2 to see if they need swapping over. In this example they do, because seven is higher than an ace. After the swap the cards look like this

1 2 3 4

The next step is to compare the cards in position 2 and 3 to see if any swapping needs doing. In this case it doesn't because a 7 is lower than the jack, so the cards remain in the same order.

The cards in position 3 and 4 are then compared, and this time they do need swapping, because the jack is higher than the 6. After they are swapped the order of the cards looks like this :

1 2 3 4

Now one full "pass" has been made through the cards, and they are starting to look a bit more sorted, although not totally sorted yet. In that pass through the cards some swaps took place, so you cannot be certain that they are fully ordered. Therefore another pass has to be done through the cards ( here we go again )

The cards at position 1 and 2 are checked to see if they need swapping, they don't because the ace is lower than a 7. So the order remains the same.

The cards at position 2 and 3 are then checked, and this time they do need swapping, because 7 is higher than 6. After the cards are swapped The order of the cards looks like this :

1 2 3 4

The cards are now sorted to our eyes, but the algorithm doesn't know that yet. So it continues on, and checks the cards at positions 3 and 4. Obviously they don't need swapping.

The 2nd full pass through the cards is now complete, but a swap did take place during that pass so the algorithm cannot be sure that the cards are in sorted order still. Only after a full pass through the cards with no swaps taking place will the algorithm know that the cards are sorted, so a third pass commences.

The cards at position 1 and 2 are checked, then at positions 2 and 3 and finally at positions 3 and 4. No swaps will take place during the pass so the algorithm finishes with the knowledge that all the cards are now in a sorted order.

 

Program code- changed and added parts shown in red

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>

#define SELECTIONS 6
#define MAXBALL 49.0
#define MAXRAND 32767

int num[SELECTIONS];

void bubblesort(void)
{
int swapped=1,i,temp;

while(swapped==1)
{
swapped=0;
for(i=0;i<SELECTIONS-1;i++)
{
if(num[i]>num[i+1])
{
temp=num[i];
num[i]=num[i+1];
num[i+1]=temp;
swapped=1;
}
}
}
}

void getnum(int index)
{
float ran;
int i,done=0;

while(done==0)
{
ran=rand();
ran=((ran/MAXRAND)*MAXBALL)+1;
if(ran>MAXBALL)ran=MAXBALL;
num[index]=(int)ran;
done=1;
for(i=0;i<index;i++)
if(num[index]==num[i])done=0;
}
}

void main(void)
{
int i,done=0;
unsigned char key;

srand(Time());
while(done==0)
{
clrscr();
printf("Your lottery ticket numbers for this week\n\n");
for(i=0;i<SELECTIONS;i++)
getnum(i);
bubblesort();
for(i=0;i<SELECTIONS;i++)
printf("%d ",num[i]);

printf("\n\nPress X to exit or any other key to select different numbers\n\n");
key=getch();
if(key=='x'||key=='X')done=1;
}
printf("Good luck, and if you win, please remember me !");
}

 

Description of the program code
If you scan straight down to the main() function, some changes have taken place there. These were needed because the previous version of the program generated and displayed the ticket numbers in the same loop. With this version, they are generated, sorted, and then displayed, which requires two for loops to be used. Sandwiched in between the two for loops is a call to the bubblesort function which sorts the ticket numbers into order using the bubblesort algorithm ( explained above ). The implementation of this function is explained in more detail below :

The bubblesort function doesn't return any values because it doesn't need to, or it doesn't accept any parameters because it has all the information it requires as the array it will be sorting ( num ) is defined as global.

The swapped local variable that is declared is set to the value 1, this is the variable that is used to detect whether any swaps have taken place in each pass or not. It is set to 1 so that initially it will enter the while loop that will follow.

The while loop ( while(swapped==1) ) is the loop used for the complete "passes" through the array, it will continue to do a full pass through the data until no swaps have taken place, in other words when the swapped variable is set as 0 at the end of the loop.

At the start of each pass in the while loop the swapped variable is set to 0 to indicate that no swaps have taken place ( yet ).

The next for loop is used to perform the passes through the array ( for(i=0;i<SELECTIONS-1;i++) ). Notice the SELECTIONS - 1 part, it will not go to the end of the array, it starts at position 0 and goes to position 4 ( 6 - 1 is 5, but it is set to "less than 5" which is 4 ). Within this for loop the checking of the order takes place in the if line : if(num[i]>num[i+1]) . So in the for loop it will check the numbers at array positions 0 and 1, then at 1 and 2, then 2 and 3, then 3 and 4 and finally at index positions 4 and 5 ( i +1 ).

If a the condition in the if statement results in true ( num[i]>num[i+1] ), then the numbers in the array positions need swapping around. The following code does this and sets the swapped variable so that the function will go through another pass.

temp=num[i];
num[i]=num[i+1];
num[i+1]=temp;
swapped=1;

Swapping the contents of the values in two variables isn't as straight-forward as you'd think. Before continuing on with a description of this program look at the sample program below ( It doesn't work right though ) :

#include <stdio.h>

void main(void)
{
int a=10,b=20;
a=b;
b=a;
printf("The values of variables a and b are %d and %d respectively",a,b);
}

The output from the program will be :

The values of variables a and b are 20 and 20 respectively

A slow trace through the code will show why this happens. Firstly the value of variable a is 10 and the value of variable b is 20.

Then the value of variable a is set to the value of variable b, so at this point both a and b are 20 ( the 10 has been overwritten and lost )

Then the value of variable b is set to the value of variable a ( which is now 20 ), and the resulting output is that both variables hold 20 !

To overcome this you can create a temporary variable to hold the original value of the a variable so that it can be remembered. The following code does work.

#include <stdio.h>

void main(void)
{
int a=10,b=20,temp;
temp=a;
a=b;
b=temp;
printf("The values of variables a and b are %d and %d respectively",a,b);
}

The values of variables a and b are 20 and 10 respectively

This is the way the swapping of the values in the array positions num[i] and num[i+1] is done.

 

Summary
This page explained how the bubblesort algorithm works and also showed an implementation of it in the lottery number selection program. The bubblesort algorithm is so named because the numbers seems to "bubble" through the array. For example, in the cards example, place a king at the start and watch it bubble all the way through the cards to the end.

The problem with swapping the contents of two variables was also shown, and the way that is used to get around it.

The program produced is a fully functional lottery number selection program with a sorted output of selected numbers. There are probably a few shareware or freeware downloadable programs on the Internet that do the same thing, maybe with a few more features like number history etc.. but basically the same type of thing.

About 90% of people who started reading page one have probably gone by the wayside now with learning to program. These last four pages will account for the majority of people giving up. This is the reason, I believe that people don't go further with programming, it starts to look difficult. If you glance at the code for the program on this page, it's scary, but to think after 17 programs you can follow it through, is a real achievement and one in which now classes you as a computer programmer. In other words, if you are still here, you've cracked it ! It's downhill from now on..

 

Tasks

There are no tasks for this page, but there are always programs to be written. There is enough info now to begin to think of some programs to write and implement them.

 

Go back a page Continue on to next page >>

(c) J.C.Spooner 2001