if minIndex has been updated, swap the values at minIndex and currentIndex. If the value of the index of the current loop is less than the value of the item at minIndex, update minIndex with the new lowest value index.Loop through all indexes that proceed the currentIndex.This index will represent the index with the lowest value so we named it minIndex. Loop from the beginning of the array to the second to last item.Selection Sort executes in the following steps: This process goes on till whole array gets sorted. Then we again look for smallest element in the remaining array (excluding first element) and swap it with second element. Once we find it, we swap smallest element with the first element of array. If ( minIndex != currentIndex ): temp = array array = array array = temp currentIndex += 1 if _name_ = '_main_' : array = selection_sort ( array ) print ( array ) Walkthrough The idea of selection sort is simple: We traverse the whole array to find smallest element. MinIndex = i i += 1 # step 5: if minIndex has been updated, swap the values at minIndex and currentIndex If ( array < array ): # update minIndex with the new lowest value index # than the value of the item at minIndex, update minIndex I = currentIndex + 1 while ( i < len ( array )): # step 4: if the value of the index of the current loop is less MinIndex = currentIndex # step 3: loop through all indexes that proceed the currentIndex Public class SelectionSort let array = selectionSort ( array ) alert ( array )ĭef selection_sort ( array ): # step 1: loop from the beginning of the array to the second to last itemĬurrentIndex = 0 while ( currentIndex < len ( array ) - 1 ): # step 2: save a copy of the currentIndex
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |