What is wrong with this merge to sort python code?

Here is the code for merge sort. The code works very well and sorts the numbers. But if we are looking for big data that needs to be sorted, something will go wrong. The data to be sorted contains numbers that are not repeated. But after sorting, there are certain numbers that are repeated many times. I do not understand why this is so. And this happens when I give a dataset of 100,000 numbers. when small data needs to be sorted, the code works very well.

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


print("select the file: ")
file_name =  tkFileDialog.askopenfile(mode='r', title='Select word list file')
inv_data = np.loadtxt(file_name,dtype='float', comments='#', delimiter=None, converters=None, skiprows=0, usecols=None,
                unpack=False, ndmin=0)
mergeSort(inv_data)
print("sorted list :", inv_data)

The dataset is located here at the following link http://spark-public.s3.amazonaws.com/algo1/programming_prob/IntegerArray.txt

+4
source share
1

, Python, . NumPy. , NumPy, ,

lefthalf = alist[:mid]
righthalf = alist[mid:]

, .

alist lefthalf righthalf, ; lefthalf, .

:

>>> l = np.arange(10,0,-1)
>>> l
array([10,  9,  8,  7,  6,  5,  4,  3,  2,  1])
>>> mergeSort(l)
>>> l
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
+5

Source: https://habr.com/ru/post/1539429/


All Articles