Given an array of integers, sort the elements in the array in ascending order. The selection sort algorithm should be used to solve this problem.
Examples
{1} is sorted to {1}
{1, 2, 3} is sorted to {1, 2, 3}
{3, 2, 1} is sorted to {1, 2, 3}
{4, 2, -3, 6, 1} is sorted to {-3, 1, 2, 4, 6}
class Solution(object):
def solve(self, array):
if len(array) <= 1 :
return array
for n in range(len(array)-1,0,-1):
largest_index = 0
for j in range(n+1):
if array[j] > array[largest_index] :
largest_index = j
array[n],array[largest_index] = array[largest_index],array[n]
return array
网友评论