Selection sort O (n ^ 2)

Also from books


#Very time consuming but easiest sort
#I will look at it in order from the beginning, because it will decrease over time
#Real O(n x 1/2 x n)Becomes
#O because it is ignored in the Big O notation(n^2)Write

def findSmallest(arr):
    smallest = arr[0]        #Store the smallest value
    smallest_index  = 0 #Stores the index of the smallest value
    for i in range(1, len(arr)):
        if arr[i] < smallest: #First array[0]Compare with
            smallest = arr[i]
            smallest_index = i
    return smallest_index

#Selection sort using this function
def selectionSort(arr):   #Sort array
    newArr = []
    for i in range(len(arr)):
        smallest = findSmallest(arr)   #Find the smallest element in the array
        newArr.append(arr.pop(smallest)) #Add to new array
    return newArr

print selectionSort([5,3,6,2,10])  #Sorted

Results sorted in order [2,3,5,6,10]

Recommended Posts

Selection sort O (n ^ 2)
Selection Sort
Prime factorization with O (n ^ (1/4))
sort
I wrote the selection sort in C