0

I took this merge sort example from a blog. I'm just starting to study merge sort and I wanted to check its speed compared to python's default sorting algorithm. With short random generated lists it's not very noticeable but with a big list, like one with 1,000,000 integers, it takes around 10 seconds, while python's default sorting algorithm doesn't even comes close to 1 second.

import random
import time


def mergeSort(alist):

 if len(alist)>1:
   mid = len(alist)//2
   lefthalf = alist[:mid]
   righthalf = alist[mid:]

   mergeSort(lefthalf)
   mergeSort(righthalf)

   i=0
   j=0
   k=0

   while i < len(lefthalf) and j < len(righthalf):
       if lefthalf[i] < righthalf[j]:
           alist[k]=lefthalf[i]
           i=i+1
       else:
           alist[k]=righthalf[j]
           j=j+1
       k=k+1

   while i < len(lefthalf):
       alist[k]=lefthalf[i]
       i=i+1
       k=k+1

   while j < len(righthalf):
       alist[k]=righthalf[j]
       j=j+1
       k=k+1


array = [random.randint(0,1000) for a in range(0,10000)]

#print "original random generated array:",array

start = time.clock()

sorted_array = mergeSort(array)

#print "\nSorted array: ", sorted_array

print "Time: ", str(time.clock() - start)

start1 = time.clock()

array = array.sort()

print "Time: ", str(time.clock() - start1)
3
  • 7
    Maybe Python's sort is not written in Python? Commented Mar 25, 2018 at 21:42
  • 5
    1) Python's sort is written in C. 2) Python's sort is a TimSort, not a MergeSort. You're comparing apples and oranges. Commented Mar 25, 2018 at 21:43
  • 1
    See here stackoverflow.com/questions/1517347/… Commented Mar 25, 2018 at 21:43

1 Answer 1

1

Python is great for a lot of things but compared to many other languages it runs very slowly. The built-in functions in your typical Python distribution are written in C which is much faster than the equivalent Python code.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.