Value of min_index concept not understood properly

In the selection sort algorithm why do we need to initialize the value of min_index variable with i.

for(int i = 0; i < n -1 ; ++i)

{

    int min_index;

    for(int j = i; j < n; ++j)
    {
        if(a[j] < a[i])


        min_index = j;

    }
    swap(a[i], a[min_index]);  

}

Here inside the jth loop I am comparing a[j] with a[i].

Now if I just initize the min_index variable it gives me weong output.

Can you explain me why we need to initialixe value of min_index with i although we are replacing with j in the second loop.

Please Help!!!:persevere:

By the second loop, you check that if there is a smaller number in the subarray starting from index i+1, so that you can swap ith number with it. In case you do not find any such smaller number, then swapping is not needed(or you can swap the ith number with itself). So to handle this case, minindex is initialized to i

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.