Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected Result

I am writing a program to sort array using this Minimum function but getting unexpected result

 def Minimum(Arr,starting,ending):
    small = 0
    for i in range(starting,ending-1):
      #if i+1 != ending:
        if Arr[small] > Arr[i+1]:
           small = i + 1
    return small
x=[-5,-3,-4,0,2,3,1,324,321]
def Sort4(Arr):
    for i in range(len(Arr)-1):
        temp = Arr[i]
        value = Minimum(Arr, i, len(Arr))
        Arr[i] = Arr[value]
        Arr[value] = temp
            
Sort4(x)
print(x)

Result:[324, -5, -3, -4, 0, 1, 2, 3, 321] but i want my results [-5,-4,-3,0,1,2,3,321,324] i don,t know why i am getting wrong result

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your minimum function doesn’t function properly. You need to check for the minimum within the (starting, ending) subarray:

def Minimum(Arr, starting, ending):
    small = starting  # assume first element is the smallest
    for i in range(starting, ending): # go through each index in range
        if Arr[small] > Arr[i]:  # compare with current smallest
            small = i   # update smallest if required
    return small

Which makes the sort work properly:

x = [-5, -3, -4, 0, 2, 3, 1, 324, 321]


def Sort4(Arr):
    for i in range(len(Arr) - 1):
        temp = Arr[i]
        value = Minimum(Arr, i, len(Arr))
        Arr[i] = Arr[value]
        Arr[value] = temp


Sort4(x)
print(x)

Result:

[-5, -4, -3, 0, 1, 2, 3, 321, 324]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading