2016-11-15 21 views
0

我想在不使用內置排序方法(如「sorted」或.sort)的情況下對python中的3個數字進行排序。如何在不使用內置方法的情況下對Python中的數字進行排序

說我有數字...

2,500,25,15,12

我想輸出2,12,15,25,500

我想模仿如何對Python作品內置的函數進行排序,但找不到它的源代碼。

對於3號我所做的:

msg = "Give me a number: " 
pfix = " is the greatest" 


a = int(input(msg)) 
b = int(input(msg)) 
c = int(input(msg)) 
nums = [] 

if a>b and a>c: 
    nums.append(a) 
elif b>a and b>c: 
    nums.append(b) 
else: 
    nums.append(c) 


if a>b and b>c: 
    nums.append(b) 
elif a>b and b>c: 
    nums.append(b) 
elif a>c and c>b: 
    nums.append(c) 
elif b>a and a>c: 
    nums.append(a) 
elif b>c and c>a: 
    nums.append(c) 
elif c>a and a>b: 
    nums.append(a) 
elif c>b and b>a: 
    nums.append(b) 

if a<b and a<c: 
    nums.append(a) 
elif b<a and b<c: 
    nums.append(b) 
elif c<b and c<a: 
    nums.append(c) 

print(nums) 

我知道這是個不錯的方法,因爲它只會爲3號工作。我需要使用一個for循環

像數的無限名單一起想...

def num_sort(_list): 
    for i in range(0, len(_list)): 
    ... 

而且使用這樣

print(num_sort([2, 500, 25, 15, 12])) 

,我將如何去獲得特定種類? 例如升序或降序...

我知道它像重新發明輪子,但我被告知我需要做我自己的方法。

你會做什麼?

在此先感謝。

+0

閱讀了關於排序方法:泡沫,插入,合併,快速 – gidim

+1

不粗魯,但是,如果你被要求使自己的方法,你爲什麼要問我們呢?你知道任何排序算法嗎? –

+0

我把上面的代碼交給他們,他們選擇接受,因爲不管它有多糟糕,它都會按照他們的要求去做。 3個數字。我想知道應該如何反思。 –

回答

0

快速排序算法中 - http://www.algolist.net/Algorithms/Sorting/Quicksort

def sort(array): 
    less = [] 
    equal = [] 
    greater = [] 

    if len(array) > 1: 
     pivot = array[0] 
     for x in array: 
      if x < pivot: 
       less.append(x) 
      if x == pivot: 
       equal.append(x) 
      if x > pivot: 
       greater.append(x) 
     return sort(less)+equal+sort(greater) 
    else: 
     return array 
print(sort([12,4,5,6,7,3,1,15])) 
相關問題