//
// SORTER.C -- demonstration of C run-time library routines
//
//    seed the random number generator 
//    generate COUNT random numbers
//    display them
//    sort them 
//    display them
//    use malloc and free to manage memory for storing the numbers



#include <stdlib.h>
#include <limits.h>
#include <time.h>
#include <string.h>
#include <search.h>
#include <stdio.h>

#include <crtdll.h>

#define COUNT 64

void display (int *beginning);
int compare (const void *arg1, const void *arg2);

//void far _loadds sorter()
void _loadds sorter()
{
int *random;
int *ptr;
char i;

//  generate the random numbers

    random = malloc(sizeof(int) * COUNT);
    srand( (unsigned) time(NULL));
    ptr = random;
    for (i= 0; i < COUNT; i++)
    {
        *ptr = rand();
        ptr++;
    }

//  display them
    printf("The generated random numbers are:\n");
    display(random);

//  sort them
    qsort( (void *)random, COUNT, sizeof(int), compare);

//  display them sorted
    printf("\n\n");
    printf("The sorted random numbers are:\n");
    display(random);

//  free the memory
    free(random);
}


void display (int *beginning)
{
char i,j;
div_t div_result;
char width;
char per_line;
int *ptr;
char *buffer;

    buffer = malloc(80);
    itoa(INT_MAX, buffer, 10);
    width = strlen(buffer)+1;
    free(buffer);
    per_line = 80/width;
    div_result = div(COUNT, per_line);

    ptr = beginning;
    for (i=0; i < div_result.quot; i++)
    {
        for (j=0; j < per_line; j++)
        {
            printf("%*d", width, *ptr);
            ptr++;
        }
        printf("\n");
     }
    if (div_result.rem != 0)
    {
        for (i = 0; i < div_result.rem; i++)
        {
            printf("%*d", width, *ptr);
            ptr++;
        }
        printf("\n");
    }
}

int compare (const void *arg1, const void *arg2)
{
int *Parg1;
int *Parg2;

    Parg1 = (int *) arg1;
    Parg2 = (int *) arg2;

    if (*Parg1 < *Parg2)
        return -1;
    else
        if (*Parg1 == *Parg2)
            return 0;
        else
            return 1;
}

unsigned far pascal Start(void)  /* autoinit entry point */
{
//      _CRT_DLLinit();	  Needed if doing printf() or malloc() in Start()
        return 1;
}
