Home > database >  C Basic Sorting Algorithm through Command Arguments
C Basic Sorting Algorithm through Command Arguments

Time:01-24

I'm having some problems with the code below.

My goal with it is to sort an array created from the int value of command arguments ex using the argument Hello 125 17 -6 should give:

Unsorted: 0 125 17 -6
Sorted: -6 0 17 125

The problem is an extra value is included and is printed out as: Unsorted: -858993460 0 125 17 -6 Sorted: -6 0 17 125

I dont know what this value represents and why my data[] array registers it.

Basic Sorting code:

void mySort(int d[], unsigned int n) {

     int i, j, key;

     for (i = 0; i < n; i  ) {

         key = d[i];
         j = i - 1;

         while (j >= 0 && d[j] > key) {

             d[j   1] = d[j];
             j = j - 1;

         }

         d[j   1] = key;
    }

}

Main code:

int main(int argc, char* argv[]) {
int data[1000];
int nDataItems;
int i;

if (argc > 1) {

    nDataItems = argc;
    fprintf(stderr, "The command line arguments are:\n");

    for (i = 1; i < argc; i  ) { /* Prints each arg as a string, int and hex */

        fprintf(stderr, "   argv[%d] (as string): %s\n"
            "              (as int): %d\n"
            "       (as int in hex): %X\n\n",
            i, argv[i], atoi(argv[i]), atoi(argv[i]));

        data[i] = atoi(argv[i]);/* stores integer of each argument value */

    }

}else {
    fprintf(stderr, "There were no command line arguments.\n");

    /* Default Test data */
    nDataItems = 4;
    data[0] = 10;
    data[1] = 20;
    data[2] = 30;
    data[3] = 40;

}

printf("Unsorted Array: ");

for (i = 0; i < nDataItems; i  ) {

    printf(" %d ", data[i]);


}

mySort(data, nDataItems);

/* Check that the data array is sorted. */
for (i = 0; i < nDataItems - 1; i  ) {

    if (data[i] > data[i   1]) {

        fprintf(stderr, "Sort error: data[%d] (= %d)"
            " should be <= data[%d] (= %d)- -aborting\n",
            i, data[i], i   1, data[i   1]);

        exit(1); /* exit(1) = exit failure*/

    }

}

/* Print sorted array to stdout */
printf("\nSorted Array: ");

if (argc > 1) {
    for (i = 1; i < nDataItems; i  ) {

        printf(" %d ", data[i]);

    }
}
else {
    for (i = 0; i < nDataItems; i  ) {

        printf(" %d ", data[i]);

    }
}

exit(0); /* exit(0) = exit success*/

}

Help would be greately apreciated

CodePudding user response:

You should initialize the data[0]. If you don't assign a value, it will take a random value.

This line

data[i] = atoi(argv[i]);/* stores integer of each argument value */

should be,

data[i - 1] = atoi(argv[i]);/* stores integer of each argument value */
  •  Tags:  
  • Related