-1

i am trying to create function which will show numbers from smallest to largest, using def, not by python built in function like sort(), how can i do this ?

i have tried to search in google to fix this problem

# Data structures --> arrays

print('Welcome')
number = []
nums_len = int(input('Enter how many numbers: '))

def enter_nums():
    for nums in range(nums_len):
        num = int(input('Enter numbers: '))
        number.append(num)
enter_nums()

# O(N) search running speed
maximum = number[0]
minimum = number[0]

for nums in number:
    if nums > maximum:
        maximum = nums
print(maximum, 'is a max number')
for nums in number:
    if nums < minimum:
        minimum = nums
print(minimum, 'is a min number')

i already set up application which shows min and max numbers from the list, but i need it to show me numbers from smallest to largest

  • Is this a quiz or homework problem? – redbow_kimee Sep 01 '19 at 22:29
  • homework problem – Luka Morchiladze Sep 01 '19 at 22:30
  • Suggest you try implementing bubble sort, it's pretty quick and easy. Hint: Python has a built in swap function. a = [1,2,3], then you can say a[0],a[1] = a[1],a[0] and your list is now a = [2, 1, 3]. Of course you only want to do that if a[0] > a[1]... – neutrino_logic Sep 01 '19 at 22:58
  • Since this is a homework problem, I'd strongly suggest checking your school's academic honesty policy before submitting an answer from stack overflow. It sounds as if your instructors would like you to implement a sort function, or come up with a creative way to print an unordered list in order. Try reading through some of the [wikipedia pages on sorting](https://en.wikipedia.org/wiki/Sorting) for inspiration on choosing a sort algorithm and implementing it. You could come up with another solution such as repeatedly traversing your list of numbers and printing then removing the minimum, or rep – redbow_kimee Sep 01 '19 at 22:40

1 Answers1

-1

They're asking you to implement sort itself in some manner. Here's one of the simpler sort algorithms, insertion sort. Note it uses an internal helper function:

def sort_insertion(numbers):
    def insert(numbers, position, value):
        i = position - 1
        while i >= 0 and numbers[i] > value:
            numbers[i + 1] = numbers[i]
            i = i - 1
        numbers[i + 1] = value

    for x in range(1, len(numbers))
        insert(numbers, x, numbers[x])
    return numbers

Be sure to walk through these examples and see how each value changes as the algorithm cycles. *PS My resource for algorithms is Algorithms in a Nutshell, A Practical Guide, Heineman, Pollice & Selkow, O'Reilly. It's got all the basics and some complex ones, in pseudocode or C, C++, Java, Python. Cheaper than most textbooks. **PPS copying and pasting code will not help you pass exams!

neutrino_logic
  • 1,289
  • 1
  • 6
  • 11