My sorting algorithm in python freezes sometimes during runtime, can someone take a look? -
basically i've been trying is, i'm picking out smallest , largest unsorted list, appending them new list, popping smallest , largest old unsorted list , doing process on , on until end sorted list. please take @ code .
import random import time stack = [] #sorted list numbersarray = [] #unsorted list usersize = int(input("how many digits want in array? ")) #numberofinputs limit = 0 counter = 0 while limit <= usersize: numbersarray.append(random.randint(0,20)) #randomly input numbers array limit = limit + 1 print(numbersarray) #prints current unsorted array start_time = time.time() #starts clock subtractor = 0 #used later in code changing index while len(numbersarray) != 0: = 0 largest = numbersarray[i] size = len(numbersarray) -1 smallest = numbersarray[i] while (i < len(numbersarray)): if numbersarray[i] >= largest: largest = numbersarray[i] index = elif numbersarray[i] <= smallest: smallest = numbersarray[i] indextwo = = i+1 if (len(numbersarray) == 1): #this checks if there's 1 number left. entry = int(stacksize/2 + 1) stack.insert(entry,numbersarray[0]) break else: if indextwo > index: numbersarray.pop(indextwo) numbersarray.pop(index) elif index > indextwo: numbersarray.pop(index) numbersarray.pop(indextwo) stacksize = len(stack) if stacksize == 0: stack.append(smallest) stack.append(largest) elif stacksize != 0: stack.insert(stacksize-subtractor,largest) #the subtractor dynamically changing index of insertion. stack.insert(0+subtractor,smallest) subtractor = subtractor + 1 print(stack) print("--- %s seconds ---" % (time.time() - start_time))
you have doubly nested while loop in scan whole array max
, min
s , proceed .pop
elements list in arbitrary positions.
considering pop
of o(n)
complexity items not in end of list; approach highly inefficient , pass out/freeze large values of usersize
. that's why, i'm guessing, "sometimes" in title happens when usersize
large.
in short, case need find better algorithm solve problem.
Comments
Post a Comment