I'm attempting to sort a pointer array using a bubbleSort (yes I know how inefficient it is but for the purpose of this program it'll work just fine) and I'm having trouble getting the sort to iterate through my pointer array. This program requires that no array notation be used i.e. '[ ]' brackets, just pointer arithmetic. The user also defines the size of the pointer array with a command line argument ( 'a.out 5' where 5 would be the array size). I believe the problem in my sort lies in the if() statement but I'm unsure on how to fix it. Can anyone help?
The program's fairly unrefined at this point so sorry for the mess:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void bubbleSort(int *p, int array_size);
int main(int argc, char **argv)
{
int i, j, q;
int *p, *b;
++argv;
q=atoi(*argv);
p= calloc(q, sizeof(int));
b=p;
srand( (unsigned)time( NULL ) );
if (q>0){
printf("Unsorted:\n");
for (i = 0; i < q; i++) {
*b = (rand()%100);
printf("%d\n",*b);
b++;
}
}
else {
printf("Invalid Entry\n");
return 0;
}
bubbleSort(b, q);
for (i = 0; i < q; i++)
{
printf("%i\n", *p);
}
free(b);
}
void bubbleSort(int *p, int array_size)
{
int i, j, temp;
for (i = (array_size - 1); i >= 0; i--)
{
for (j = 1; j <= i; j++)
{
if (*p-- > *p)
{
temp = *p--;
*p-- = *p;
*p = temp;
}
}
}
}