Page 248 - Programming Microcontrollers in C
P. 248

Sorting Programs     233

                          as was done above, but also, you can swap pointers from an array of
                          pointers to order a set of data that would be difficult to swap. For
                          example, if you had a collection of words, you could use a srtcmp()
                          routine to determine whether one word was lexically larger than the
                          other and then write a swap routine that merely swapped the pointers
                          to these words rather than swapping the words themselves. This
                          approach to sorting a list of words is relatively simple. On the other
                          hand, it would be extremely difficult—nearly impossible, in fact—
                          to sort a list of words that are packed into memory.
                              The following program is used to test the performance of the
                          above sort routines. The program simply makes an array of 11 entries
                          and sorts the array by both the Shell sort and the quick sort. The
                          result of this program is printed out below.

                   #include <stdio.h>
                   main()
                   {
                       int v[]={81,99,23,808,3,77,18,27,128,360,550};
                       int i,k[11];
                       for (i=0;i<11;i++)
                              k[i]=v[i];
                       shell_sort(k,11);
                       for( i=0;i<11;i++)
                              printf (“%d “,k[i]);
                       printf(“\n”);
                       quick_sort(v, 0,11 -1);
                       for( i=0; i<11; i++)
                              printf(“%d “,v[i]);
                       printf(“\n”);
                   }

                          The original array is not printed out by the program, but the order of
                          the array is seen in the above listing. The two sort programs sort the
                          values correctly.

                   3 18 23 27 77 81 99 128 360 505 808
                   3 18 23 27 77 81 99 128 360 505 808
                          The quick sort routine is not the best example of recursive
                          programming. Usually, the use of recursion results in a program that
                          is significantly shorter than would be expected with conventional
   243   244   245   246   247   248   249   250   251   252   253