Insertion Sort algorithm - list of names

I am trying to use an insertion sort algorithm to sort out a list of names inputted by the user in the command line prompt. This code compiles and runs just fine, however when I try to get the sorting in order and reverse order, something must be missing because the order is all wrong. Somewhere in the while loop something is missing. Below is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void print_array( char **, int);
void insertion_sort( char **, int );
void reverse_sort( char **, int );

char ** names;

int main( int argc, char * argv[] )
{
   names = (char**) malloc(sizeof(char*) * argc );
  
   if( argc == 1 )
   {
      printf( "Please include a list of names\n!" ); 
      return 0;
   }

   for( int i = 1; i < argc; i++)
   {
        names[ i - 1 ] = argv[ i ];
   }
   
    printf( "Before sort:\n" );
    print_array( names, argc - 1 );

    printf( "In order:\n" );
    insertion_sort( names, argc - 1 );
    print_array( names, argc - 1 );

    printf( "In reverse order:\n" );
    reverse_sort( names, argc - 1 );
    print_array( names, argc - 1 );

    getchar();
    return 0;
}

void print_array( char ** array, int size )
{
    int i = 0;
    for( i = 0; i < size; i++ )
    {
      printf( "%d %s\n", i + 1, array[ i ] );
    }
}

void insertion_sort( char ** array, int size )
{
    int i = 0;
    int j = 0;
    char * name;
    for( i = 0; i < size; i++ )
    {
        name = array[ i ];
        j = i - 1;
        while( j >= 0 && strcmp(array[ j ], array[ j + 1 ]) > 0 )
        {
            array[ j + 1 ] = array[ j ];
            j = j - 1;
        }
        array[ j + 1 ] = name;
    }
}

void reverse_sort( char ** array, int size )
{
    int i = 0;
    int j = 0;
    char * name;
    for( i = 0; i < size; i++ )
    {
        name = array[ i ];
        j = i - 1;
        while( j >= 0 && strcmp(array[ j ], array[ j + 1 ]) < 0 )
        {
            array[ j + 1 ] = array[ j ];
            j = j - 1;
        }
        array[ j + 1 ] = name;
    }
}


The output is as follows:


Before sort:
carl
tom
bob
In order:
carl
bob
tom
Reverse order:
carl
tom
bob


Ideas?
The right hand operand for the comparison function should be the element you're trying to insert, not the element you just shifted forward.
Thanks very much, helios. It took me a bit of time to find out which element you were talking about. Once I figured it out, I felt like a dope. Thanks for helping clear up this issue. It was driving me nuts!
Topic archived. No new replies allowed.