In selection sort, if we have two duplicate elements, what is the behavior of the algorithm?

Your code would do the following:

arr[] = 1, 5, 2, 4, 3

// find the max from arr[0..4]
// substitute it with the index 0, if it is not of that index already
arr[] = 5, 1, 2, 4, 3

// find the max from arr[1..4]
// substitute it with the index 1, if it is not of that index already
arr[] = 5, 4, 2, 1, 3 

// find the max from arr[2..4]
// substitute it with the index 2, if it is not of that index already 
arr[] = 5, 4, 3, 1, 2

// find the max from arr[3..4]
// substitute it with the index 3, if it is not of that index already 
arr[] = 5, 4, 3, 2, 1

The substitute it with the index i, if it is not of that index already is that if statement


For a longer array, with duplicates, check this Kotlin Playground Code I created for you. You can change the array as you wish, and you can trace the switching of the values.

Browse More Popular Posts

Leave a Comment