Search code examples
c++csortingquicksortbubble-sort

sorting gives wrong output for the element at last position


I am trying to clear some basic concepts os programming. I preferred doing sorting for this. Below is my code:

#include<stdio.h>
#include<malloc.h>
#include <string.h>


main()
{ 
    int array[9]={5,2,7,4,7,6,9,8,1,3};
    int min,i,j,temp;
    for(i=0;i<10;i++)
    {
        for(j=0;j<=10;j++)
        {
            if(array[i]<array[j])
            {
                temp=array[j];
                array[j]=array[i];
                array[i]=temp;
            }
        }
    }
    printf("\n");
    for(i=0;i<10;i++)
    {
        printf("%d  ", array[i] );
    }
    printf("\n");
}

And the output is :

1  2  4  5  6  7  7  8  9  9

which is unexpected. It must be

1  2  3   4  5  6  7  7  8  9 

Could some one help me to know why this strange behavior at the end of the array. Why it repeats "9" and Where has "3" lost ? Also i appreciate if some one tell me name of best sorting (Mostly i have heard of Bubble and quick sort, but why and what is the difference that i don't know). Please dont tell me about in built functions (like qsort() and etc.) because the objective is to clear concepts You can any language to explain c/c++/ or even algorithm. Thanks


Solution

  • You specify an array of 9 elements, and yet you have 10 elements in the initialiser and in your outer loop:

    int array[9]={5,2,7,4,7,6,9,8,1,3};
           // ^- this is not the last index, but the number of elements!
    
    for(i=0;i<10;i++)
    

    And here you iterate up to index 10, which is the 11th element (index 0 is the first):

    for(j=0;j<=10;j++)
            //^- when j is 10 this is still true, but there is no array[10]
    

    To fix, change to the following:

    int array[] = {5,2,7,4,7,6,9,8,1,3};
          //  ^- leave empty and let the compiler count the elements
    const int array_len = sizeof(array) / sizeof(*array);
          //  length:     ^- whole array / ^- one element
    
    for (i = 0; i < array_len; ++i) {
        for (j = 0; j < array_len; ++j) {