InsertSort using Link List

Hey guys I'm still stuck in link list. (sigh..)

I don't have much explanation on how the program does but I'll just upload the concept image in my mind.

The problem is that it only displays special characters. But I think the problem is the InsertSort and not the display function.

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
#include <stdio.h>
#include <stdlib.h>

typedef char ElemArray;

typedef struct
{
    ElemArray *E;
    int Last;
}LIST;

void InitLIST(LIST **L)
{
    *L = (LIST*)malloc(sizeof(LIST));
    (*L)->E = (ElemArray*)malloc(sizeof(ElemArray)*10);
    (*L)->Last = 0;
}

void InsertSort(char x, LIST *L)
{
    int Position, Shift;

    L->Last++;
    for(Position=0; Position<L->Last ;Position++)
    {
        if(x>L->E[Position])
        {
            for(Shift=0; Shift>Position ; L->E[++Shift])
            {
                L->E[Position] = x;
            }
        }
    }
}

void DisplaySort(LIST *L)
{
    int i;

    for(i=0;i<L->Last;i++)
    {
        printf("%c\n", L->E[i]);
    }
}

int main(void)
{
    LIST *L;
    char x;
    int i;

    InitLIST(&L);

    for(i=0;i<=5;i++)
    {
        printf("Enter a character: ");
        fflush(stdin);
        scanf("%c", &x);
        InsertSort(x, L);
        DisplaySort(L);
    }

    free(L->E);
    free(L);
    return 0;
}


Concept image: http://i47.tinypic.com/eoydz.png
Last edited on
This doesn't look right
1
2
3
4
for(Shift=0; Shift>Position ; L->E[++Shift])
{
	L->E[Position] = x;
}



Shift>Position will never be true so the loop will never run.
1
2
3
4
5
6
7
8
9
This doesn't look right
for(Shift=0; Shift>Position ; L->E[++Shift])
{
	L->E[Position] = x;
}



Shift>Position will never be true so the loop will never run. 


Hi Peter, here's my latest revision on InsertSort;
1
2
3
4
5
6
7
8
9
10
11
12
void InsertSort(char x, LIST **L)
{
    int Position, Shift;

    for(Position=0;Position<=++(*L)->Last;Position++)
    {
        for(Shift=(*L)->Last;x>(*L)->E[Shift];Shift++)
        {
            (*L)->E[Shift] = x;
        }
    }
}


Thanks in advance. :)
Topic archived. No new replies allowed.