|
|
|
|
Posted 2004-12-04, 02:16 PM
|
|
|
|
I need to write a program that will be printed to the screen and to a text file. I need to test the function in a radom array of positive integers less than 100 of dimenstion 50.
Code:
#include <stdio.h>
#define MAXNUMS 2000
void quicksort (int *a, int lft_bnd, int rt_bnd);
void swap (int a[], int i, int j);
void print_arr (int a[], int nums);
main (int argc, char * argv[])
{
char filenm[20];
int dataarray [MAXNUMS];
int num_nums=0, i, eof;
FILE *fopen(), *flpt;
void print_arr (int dataarray[], int num_nums);
if (argc !=2)
{
printf ("proper invocation: pgm datafile\n");
exit(0); //call to undefined function 'exit' in function main[int, char **]
}
flpt = fopen(argv[1],"r"); //extra parameter in call to fopen() in function main[int, char **]
if (flpt == NULL)
{
printf ("Open failed, check data filename\n");
exit(1);
}
eof = fscanf(flpt, "%d", &dataarray[num_nums]);
num_nums=num_nums+1;
while (eof >0)
{
eof = fscanf(flpt, "%d", &dataarray [num_nums]);
num_nums=num_nums+1;
if (num_nums>2000)
{
printf ("too many numbers, increase array size and recompile\n");
exit (2);
}
}
num_nums=num_nums-1;
printf ("sorting %d numbers \n", num_nums);
printf ("the unsorted numbers are:");
print_arr (dataarray, num_nums);
quicksort (dataarray, 0, num_nums-1);
printf ("the sorted numbers are: ");
print_arr (dataarray, num_nums);
}
void quicksort (int*a, int lft_bnd, int rt_bnd)
{
int i, lft_ptr, x, rt_ptr, pivot;
void swap (int a[], int i, int j);
if (lft_bnd >= rt_bnd) return;
pivot = lft_bnd;
lft_ptr= lft_bnd;
rt_ptr=rt_bnd;
x=a[pivot];
while (lft_ptr < rt_ptr)
{
while ((a[lft_ptr] <= x) && (lft_ptr < rt_ptr))
lft_ptr = lft_ptr +1;
while (a[rt_ptr] >x)
rt_ptr = rt_ptr -1;
if (lft_ptr < rt_ptr)
swap(a, lft_ptr, rt_ptr);
}
a[lft_bnd]=a[rt_ptr];
a[rt_ptr]=x;
quicksort(a, lft_bnd, rt_ptr-1);
quicksort(a, rt_ptr+1, rt_bnd);
}
void swap (int a[], int i, int j)
{
int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
void print_arr (int a[], int nums)
{
int i;
for (i=0; i<nums; i=i+1)
{
if (i%10==0) printf("\n");
printf("%3d ",a[i]);
}
printf ("\n");
} |
|
|
|
|
|
|
|
|
|
|
|