I have written this algorithm to sort a list using bubble sort. Is this the most efficient way to sort a list?
If not, why?
What makes it less efficient and what are the alternatives present?
def BubbleSort(List):
for i in range(len(List)-1):
for Number in range(len(List)-1):
if List[Number] > List[Number+1]:
List[Number], List[Number+1] = List[Number+1], List[Number]
print(BubbleSort([5,2,1,4,3])
Thanks!
In your above algorithm, if the
lengthof your array is5, it will execute the innerif statement25times. In general when you will have a list ofnsize, it will for sure don^2operations excluding thefor loopandswapping.For a list of size
10^6, it will be10^12operations atleast.CorC++do around10^9operations per second. So this code of yours will take10^3seconds which is more than half an hour. So that's very much inefficient.There are better sorting algorithms which you can use instead of
bubble sortas they are faster than this.A lot of other techniques are also there but these are most common used.
Apart from that, you don't need to implement these algorithms as one of the most efficient one is already implemented in standard library of mostly each language from
CtoRust. You can just use that implementation and even pass you owncomparatorfunction if you want.