Python Sort Selection

This may seem like a simple question, but when I tried to implement sort sorting in Python, I don't get a sorted list. Is there something wrong with my implementation? A subset can be a problem.

source = [4,2,1,10,5,3,100] for i in range(len(source)): mini = min(source[i:]) #find minimum element min_index = source[i:].index(mini)-1 #find index of minimum element source[i:][min_index]= source[i:][0] #replace element at min_index with first element source[i:][0] = mini #replace first element with min element print source 
+7
source share
13 answers

I think there were a couple of problems.

Firstly, when your source [i:], I believe it returns a new array of the requested elements, not part of the original array, so if you change it, you do not change the original. Secondly, you subtracted 1 from the index if you do not want to.

 source = [4,2,1,10,5,3,100] for i in range(len(source)): mini = min(source[i:]) #find minimum element min_index = source[i:].index(mini) #find index of minimum element source[i + min_index] = source[i] #replace element at min_index with first element source[i] = mini #replace first element with min element print source 

This gives:

 [1, 2, 3, 4, 5, 10, 100] 
+13
source

This is how I would rewrite your code. Of course, in Python, I would just use list.sort() to sort the list, but here is sorting in Python.

We create a generator expression that returns tuples (value, i) for the value and its index from the list. Then, when min() evaluates the minimum search, it finds the smallest tuple value; since the value first goes into the tuple before the index, the value will be the important part, and min() will find the lowest value. (If there is a connection, min() will use the second part of the tuple, the index, as a tie-breaker. But for sorting, we don’t care how the connections are broken.)

Now, instead of searching the sub-list to find the value of min, and then look again at it to find out the index, we look at it once and get both the minimum value and the index.

But we really don't care about the minimum value; we care about the index. Thus, after executing min() we simply discard the actual value, but save the index. Correct the index that will be correct in the whole list (and not in the list fragment), and then we can swap them.

We use the standard Python idiom to replace two values. Python will build the tuple object in between, and then unzip that tuple to the left.

 lst = [4,2,1,10,5,3,100] for i_sortpos in range(len(lst)): # Make a generator expression to return (value, i) pairs. genexp = ((n, i) for i, n in enumerate(lst[i_sortpos:])) # Use genexp with min() to find lowest and its index. # (Use '_' for variable name for the actual value; we don't use it.) _, i_min = min(genexp) # Adjust index to be correct in full list. i_min += i_sortpos # Swap the number at i_sortpos with the lowest found. lst[i_sortpos], lst[i_min] = lst[i_min], lst[i_sortpos] print(lst) 

EDIT: And here is the clarification above. A slice from a list actually selects a new list; our code here does not need a new list, it just needs a convenient way to study subscriptions. The itertools module offers the islice() function, which returns an iterator that iterates over a list fragment. This avoids the multiple creation and destruction of lists when considering each sublist.

I believe this is the most efficient way to do sorting in Python. (You can get rid of the part where we bind the generator expression to genexp and save a few microseconds ... just make the min() call long one-line. But it's really not worth the loss of readability.)

 import itertools as it lst = [4,2,1,10,5,3,100] for i_sortpos in range(len(lst)): # Make a generator expression to return (value, i) pairs. # Use it.islice() for to look at sublist. genexp = ((n, i) for i, n in enumerate(it.islice(lst, i_sortpos, len(lst)))) # Use genexp with min() to find lowest and its index. # (Use '_' for variable name for the actual value; we don't use it.) _, i_min = min(genexp) # Adjust index to be correct in full list. i_min += i_sortpos # Swap the number at i_sortpos with the lowest found. lst[i_sortpos], lst[i_min] = lst[i_min], lst[i_sortpos] print(lst) 
+4
source

Or you can try as follows:

 arr = [5,4,3,1,6,8,10,9] # array not sorted for i in range(len(arr)): for j in range(i, len(arr)): if(arr[i] > arr[j]): arr[i], arr[j] = arr[j], arr[i] print arr 
+3
source
 def selectionSort(List_): for i in range(len(List_)):` #track the current smallest value smallIndex = i #loop from the current smallest value for j in range(i+1,len(List_)) if List_[j] < List_[smallIndex]: #if new value is less that our smallest value,change #smallest value to this smallIndex = j if smallIndex != i: #swap the values List_[smallIndex],List_[i] = List_[i],List_[smallIndex] #return sorted list return List_ 
+1
source

Find the position (first and last), swap elements, if the last one is lower.

 nums = [4,2,1,10,5,3,100] def sort(nums): ###Find the position and now first 0th element is sorted and rest is unsorted #Second iteration first 2 element is sorted for i in range(len(nums)-1): miniposition = i for j in range(i,len(nums)): if nums[j] < nums[miniposition]: miniposition = j temp = nums[i] nums[i] = nums[miniposition] nums[miniposition] = temp sort(nums) print (nums) 

The first iteration (exchanged places 4 and 1) [1, 2, 4, 10, 5, 3, 100]

 [1, 2, 4, 10, 5, 3, 100] [1, 2, 3, 10, 5, 4, 100] [1, 2, 3, 4, 5, 10, 100] [1, 2, 3, 4, 5, 10, 100] [1, 2, 3, 4, 5, 10, 100] 

Another way

 nums = [4,2,1,10,5,3,100] i = 0 while i<len(nums): #smallest element in the sublist smallest = min(nums[i:]) #index of smallest element index_of_smallest = nums.index(smallest) #swapping nums[i],nums[index_of_smallest] = nums[index_of_smallest],nums[i] i=i+1 print (nums) 
+1
source
 def ss(l): for i in range(0,len(l)): d=l.index(min(l[i:])) c=l[i] l[i]=min(l[i:]) l[d]=c print(l) #it prints each step of selection sort y=[10,9,1,5,0,6] ss(y) 
0
source
 def selSort(L): """ Find the smallest element in the list and put it (swap it) in the first location, Find the second element and put it (swap it) in the second locaiton, and so on. """ for i in range(len(L) - 1): minIndx = i minVal= L[i] j = i + 1 while j < len(L): if minVal > L[j]: minIndx = j minVal= L[j] j += 1 temp = L[i] L[i] = L[minIndx] L[minIndx] = temp return L 

Call:

 print( selSort([120,11,0,1,3,2,3,4,5,6,7,8,9,10]) ) 

Exit

 [0, 1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 120] 
0
source
 s = [1,8,4,9,3,6,2] for i in range(len(s)): maxi = max(s[0:len(s)-i]) #find max element tempi = s.index(maxi) # find index of max element temp = s[len(s)-1-i] #assign last element as temp s[len(s)-1-i] = maxi #put max element in last position s[tempi] = temp # put the element initially at last in its new print s 
0
source

here's what i find a good way to sort the list of numbers, and I hope this helps:

 list=[5,4,3,1,6,8,10,9] listsorted=[] for i in range(len(list)): x=min(list) list.remove(x) listsorted.append(x) print listsorted 

and the result will be [1, 3, 4, 5, 6, 8, 9, 10]

-one
source

I think the “accepted” answer is useless here. If we look, for example, at

 mini = min(source[i:]) #find minimum element min_index = source[i:].index(mini) #find index of minimum element 

not only is it inefficient in terms of creating list fragments unnecessarily, but they are searched unnecessarily. This is reasonably concise, but I don't think this is the best solution.

-one
source
 def Selection_Sort(Sarray): length = len(Sarray) i = 0 j = 0 for i in range(length): j = i+1 for j in range(length): if Sarray[i] < Sarray[j] t = Sarray[i] Sarray[i] = Sarray[j] Sarray[j] = t j = j+1 i = i+1 return Sarray 
-2
source

Sort selection code from the MIT online course.

 def selSort(L): for i in range(len(L) - 1): minIndx = i minVal = L[i] j = i+1 while j < len(L): if minVal > L[j]: minIndx = j minVal = L[j] j += 1 if minIndx != i: temp = L[i] L[i] = L[minIndx] L[minIndx] = temp 
-2
source
 def selectSort(L): for i in range(len(L)): print L minIndex = i minValue = L[i] j = i + 1 while j < len(L): if minValue > L[j]: minIndex = j minValue = L[j] j +=1 temp = L[i] L[i] = L[minIndex] L[minIndex] = temp 
-2
source

All Articles