1
a[] = {45, 90, 2, 50};
for (int x=0; x < MAX-1; x++)
    for (int y=0; y < MAX-x-1; y++)
        if (a[y] > a[y+1])
        {
            t=a[y];
            a[y]=a[y+1];
            a[y+1]=t;
        }
/* print sorted array */
printf("--------------------\n");
for (i=0; i < MAX; i++)
printf("%d\n",a[i]);

i've been trying to go through this code on paper so I have a better understanding bubble sort works but I keep making mistakes in keeping count of the variables and losing my place in the loops.

Is there a model or method to solve this program on paper?

1
  • 1
    I can't say anything about "paper code execution", but if you're struggling to understand bubble sort, I suggest you to watch the lecture in which it is explained again. It is simpler than trying to understand someone else's code. Jul 25 '15 at 18:50
1

The most used way I've seen (and the one I use when needed) is to make a column for each variable in the program, writing its name on top. When the variable is changes value in the program, you also change the value on paper, striking the previous value. Write your arrays vertically as the are probably going to take the most space. Don't use pencil and erase the values as this is going to make the process more difficult. Just strike the previous value out and write the new one underneath. For example it might look something like this:

+---------------------------------------+
|                  sort                 |
+---------------------------------------+
| n | i | j |           values          |
+---+---+---+---------------------------+
| 7 | 0 | 0 | 3 | 2 | 1 | 5 | 7 | 0 | 3 |
+---+---+---+---+---+---+---+---+---+---+
|   |   | 1 | 2 | 3 | 1 | 5 | 7 | 0 | 3 |
+---+---+---+---+---+---+---+---+---+---+
|   |   | 2 | 2 | 1 | 3 | 5 | 7 | 0 | 3 |
+---+---+---+---+---+---+---+---+---+---+
|   |   | 3 |   |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+---+---+

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .