The min function is not correct. Sometimes the third argument is an index, other times it is an array value. You compare array values with indices. Also it appears like it would find the min in the entire array whereas it needs to do that only for the unsorted part of the array.

