Question

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

Was it helpful?

Solution 3

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) {

OTHER TIPS

for(j=0;j<=10;j++) will give you undefined behaviour since you're accessing outside the array bounds with your subsequent array[j].

int array[9]={5,2,7,4,7,6,9,8,1,3}; is also unbalanced, you need int array[10] since you have 10 elements in your initialiser list. Better still, let the compiler do the work for you and write int array[]. This is why 3 is currently omitted from your output (notwithstanding the undefined behaviour).

array[9]; i < 10; j <= 10. array index out of bounds. undefined behaviour.

i and j should be checked like i < 9 and j < 9

int array[9]={5,2,7,4,7,6,9,8,1,3};

And you have 10 elements in that array.

Firstly, any code should be added using the code button so that it is formatted properly and easy to read.

Secondly, you're array is too small. It's size is 9 but you have 10 items.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top