Bubble sort omits last index

Here's the 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
#include<stdio.h>

int BubbleSort()
{
    int List[] = {96, 59, 74, 32, 27, 64, 23};
    int NoMoreSwaps;
    int Temp, i;
    
    printf("The initial elements list to sort:\n\n");
    for (i = 0; i < 7; i++)
    {
        printf("%d\n", List[i]);
    }
    
    do
    {
       NoMoreSwaps = 1;
       for (int Index = 0; Index < 7; Index++)
       {
           if (List[Index] > List[Index + 1])
           {
               NoMoreSwaps = 0;
               Temp = List[Index];
               List[Index] = List[Index + 1];
               List[Index + 1] = Temp;              
           }    
               
       }
       
    }
    while (NoMoreSwaps != 1);
    
    printf("A sorted element list:\n");
    for (i = 0; i < 7; i++)
    {
        printf("%d\n", List[i]);
    }
    
}

int main()
{
    
        BubbleSort();
        
    return 0;
}


The output prints:

The initial elements list to sort:

96
59
74
32
27
64
23
A sorted element list:
0
23
27
32
59
64
74

RUN SUCCESSFUL (total time: 522ms)


Why does the algorithm sets first element as 0 and omits the last index? (Should be 96)

Thanks

Janek566

EDIT:

When i change the condition part of the algorithm from:

1
2
3
4
5
6
7
8
9
10
11
for (int Index = 0; Index < 7; Index++)
       {
           if (List[Index] > List[Index + 1])
           {
               NoMoreSwaps = 0;
               Temp = List[Index];
               List[Index] = List[Index + 1];
               List[Index + 1] = Temp;              
           }    
               
       }


to:

1
2
3
4
5
6
7
8
9
10
11
for (int Index = 1; Index < 7; Index++)
       {
           if (List[Index - 1] > List[Index])
           {
               NoMoreSwaps = 0;
               Temp = List[Index - 1];
               List[Index - 1] = List[Index];
               List[Index] = Temp;              
           }    
               
       }


then the output is proper. I still don't understand though how is one different in final result from the other. Thanks
Last edited on
I believe that this happens because of lines 18 and 20. In line 18 Index changes from 0 to 6, in line 20 you access to List[Index+1], if Index equals 6 you go beyond list and start to analyze something else (0 in your case).

To correct this modify line 18 to
for (int Index = 0; Index < 6; Index++)

And general advice: introduce const Length = 7, and work with it. It will be easier for you to update the code in future. Try to avoid literals.
oh i see, thank you very much for the explanation. And thanks for the advice about the constants but since this is not for any particular purpose but just to learn how to implement algorithms in c, i simply used 7. Cheers!

Janek566
Topic archived. No new replies allowed.