Selection sort- shows incorrect result

the code shows incorrect results.but when i change min=a[i] (value of pos) to min=i(index of pos , it shows correct result. why?

@ankityadav943
Dry run the testcase
4
2 -18 45 30

A = { 2 . -18 , 45 , 30 }

First we start from i = 0.
a[i] = 2
We assign min as
min = a[i] … so min gets 2 as well,
We traverse over the array , searching for smallest element. min gets updated to -18 as it is the smallest element.
Then after the inner loop gets over , we swap min with a[i].
So a[0] becomes -18 as it gets value of min and min becomes 2.
But note that there is no change in the array position where -18 was present originally.
The new array after first iteration is A = { -18, -18, 45, 30} .
This is because we swapped with min and not in the array.
We should take the min_index rather than the min_value so we can make the changes in the array itself .

1 Like