Home > Software engineering >  Unexpected Result
Unexpected Result

Time:09-10

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

CodePudding user response:

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]
  • Related