r/programminghelp • u/potatoesintheback • Dec 24 '20
Python What sorting algorithm is this?
I was trying to implement bubble sort and I wrote this, it isn't bubble sort since I'm not comparing adjacent elements but it's like a combination of bubble sort and selection sort and still works to sort lists, so I'm wondering what this algorithm is called or if it even has a name?
(I'm aware it's inefficient because best and worst case are both O(n ^ 2))
#!/usr/bin/env python3
def sort(x):
n = len(x)
for i in range(n):
for j in range(i+1, n):
if (x[j] < x[i]):
temp = x[j]
x[j] = x[i]
x[i] = temp
return x2
u/amoliski Dec 24 '20
I think I'd call that a "Yikes Selection Sort" because all the extra swapping whenever if finds a less-than case makes me say "Yikes"- usually you just remember the index of the smallest element you find along the way, compare the remaining elements to your new smallest element, then do the swap at the end of the inner loop, but this one does the swap every time it hits a less-than, which means it could be swapping multiple times each loop.
1
u/Ar010101 Dec 24 '20
looks kinda like insertion sort to me, not sure, but the algorithm looks like it is that
2
u/MarkRems Dec 24 '20
I'd say this is a modified version of selection sort. In selection sort you find the smallest element remaining in each iteration of the main loop and then put that at the next spot. That's what this does, except instead of using another variable to keep track of the "current smallest" found you do it in place inside the array.