L-38 MCS 260 Fri 16 Nov 2001
Brackets are actually only a "syntactic sugar" in C.
We can rephrase all operations with arrays that involve
brackets, using pointer arithmetic.
/* L-38 MCS 260 Fri 16 Nov 2001 : bubble sort with pointers
This programs is a clone from the version we did not cover on Wednesday.
The major difference is that pointers are used to navigate through
the arrays. Novices are advised to observe the following order in
studying this program :
1) look first at the definition of print to understand how
pointer arithmetic is used to enumerate the elements;
2) then, in the definition of bubble sort, you find the comparison
of two adjacent numbers: *q with *(q-1);
observe that *(q-1) is different from *q-1;
3) finally, we can avoid all square brackets with dynamic
memory allocation, see test_sort for the use of calloc and free.
To sort an array of number in increasing order we build up the
sorted numbers from the beginning of the array, each time appending
to the sorted numbers the minimal element in the rest of the array.
Instead of explicitly looking for the minimal element like in sinking
sort, the minimal element "bubbles up" by comparing adjacent elements
and swapping them if necessary.
To test the sorting algorithm, we generate a random sequence of
digits. Keeping the numbers so low ensures duplicates. */
void bubble_sort ( int *a, int n );
/* arranges the n elements of a in increasing order using bubble sort */
void test_sort ( int n );
/* calls sinking_sort, generating n random integer numbers */
void print ( int *a, int n );
/* prints the n elements of a on the screen */
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main ( void )
{
int n;
srand(time(NULL));
printf("Testing bubble sort on random digits\n");
printf("Give the number of elements : ");
scanf("%d", &n);
test_sort(n);
return 0;
}
static void swap ( int *p, int *q)
/* swaps *p with *q */
{
int tmp = *p;
*p = *q;
*q = tmp;
}
void bubble_sort ( int *a, int n )
{
int *p,*q;
int i; /* i is only used to print the step counter */
for (p = a, i = 0; p < a+n-1; p++, i++)
{
for (q = a+n-1; q > p; q--)
if (*(q-1) > *q) /* compare adjacent numbers */
swap(q-1,q);
printf("Array after pass %d : \n", i+1);
print(a,n);
}
}
void test_sort ( int n )
{
int *a,*p;
a = calloc(n,sizeof(int)); /* allocate space for n integers */
for (p = a; p < a+n; p++)
*p = rand() % 10;
printf("The %d random numbers before sorting :\n", n);
print(a,n);
bubble_sort(a,n);
printf("The %d random numbers after sorting :\n", n);
print(a,n);
free(a); /* release the memory space */
}
void print ( int *a, int n )
{
int *p;
for (p = a; p < a+n; p++)
printf(" %d", *p);
printf("\n");
}