Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
AdvancedALgorithmsComplete/STD_1.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
26 lines (23 sloc)
1.76 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def SelectionSort(A): | |
''' | |
List sorting algorithm that finds smalles element in the list, puts it in the front, | |
and repeats the process with the rest of the unsorted elements | |
Input: unsorted list | |
Output: sorted list with increasing values | |
''' | |
for i in range(len(A)-1): #outer loop, goes through all indexes of A list except the last one | |
canswap = False #set flag for nessecity of a swap to False | |
minim = i #place an index of A list inside minim variable | |
for j in range(i+1,len(A)): #inner loop, goes through indexes of A list starting from current value of outer loop plus one | |
if A[j] < A[minim]: #if value under current inner loop index is smaller than value under minimum variable index | |
minim = j #replace minimum variable with current inner loop value | |
canswap = True #switch flag for necesity of a swap to True | |
if canswap == True: #if flag for necessity of a swap is set to True | |
A[i],A[minim] = A[minim],A[i] #swap the minimum value with the current value of the outer loop | |
return A #return sorted list | |
print(SelectionSort([4,5,2,8,1])) | |
#go through all indexes in the list except the last one(as we do not need sorting if there is only one element left). With each iteration indexes of a list which we went trough will be sorted and the rest will be an unsorted part | |
# put first unsorted element of the list inside the minimum variable | |
#search through rest of the unsorted part of the list (without the first element) | |
#replace current minimum variable with the smaller one that we found | |
#swap the minimum value with what is in the smallest index of unsorted part of the list |