簡體   English   中英

在沒有內置排序的情況下從給定列表中排序數字列表,如果第一個數字大於第二個數字則復制它們交換它們

[英]Order a list of numbers from given list without built-in sort, copy if first number is greater than second number swap them

我試圖實現一個 function 的方式,它與sorted(lst)基本相同,而不使用sorted(lst)var = lst.copy()但我只是不知道如何工作方式並完全遵循偽代碼中編寫的方式。

有人可以幫幫我嗎?

我的評價是:

下面是排序算法的偽代碼:

  1. 從列表的開頭開始,將每個元素與其下一個鄰居進行比較。
  2. 如果元素大於其下一個鄰居,則更改它們的位置。
  3. Go 通過列表到最后。
  4. 如果在第 2 步有任何混淆,go 到第 1 步

我現在的代碼:

def my_sort(lst):
    lst_sorted = []
    lst2 = lst.copy()
    compare = True
    while compare:
        compare = False
        num = lst2[0]
        if num not in lst_sorted:
            try:
                for x in lst2:
                    if x < num:
                        x, num = num, x
                        lst_sorted.append(num)
                    elif num < x:
                        compare = True
        else:
            compare = True
    return lst_sorted

我的教授給我的測試代碼:

def test_my_sort():
    lst_test = random.choices(range(-99, 100), k=6)
    lst_copy = lst_test.copy()
    lst_output = my_sort(lst_test)

    assert lst_copy == lst_test, "Error: my_sort (lst) changes the contents of list lst"
    assert lst_output == sorted(lst_test), \
        f"Error: my_sort ({lst_test}) returns {lst_output} instead of {sorted (lst_test)}"

if __name__ == '__main__':
    try:
        test_my_sort()
        print("Your my_sort () function works fine!")

簡單的解決方案

根據您使用標志compare的意圖和確切的評估規則,這里是一步一步的解釋:

def my_sort(lst):
    # We copy the list so that the changes are not made in the original variable.
    # We will modify lst2 from now.
    lst2 = lst.copy()
    compare = True
    while compare is True:
        # compare will remain False as long as there is no swapping
        compare=False
        # We walk the list index by index, excepted the last one
        # so we don't get an index error from the last "index+1"
        for i in range(len(lst2)-1):
            # If the first is greater than the second...
            if lst2[i]>lst2[i+1]:
                # We swap
                bump = lst2[i]
                lst2[i]=lst2[i+1]
                lst2[i+1]= bump
                # and set compare to True to ask for another iteration of the while loop
                compare=True
    return lst2

Python 中的另一種交換方式

您可以換成一行:

for i in range(len(lst2)-1):
    if lst2[i]>lst2[i+1]:
       lst2[i], lst2[i+1] = lst2[i+1], lst2[i]
       compare=True

優化冒泡排序

這種排序算法稱為Bubble Sort

有一個優化是基於觀察到的,最大值總是在一次迭代中被帶到最后的槽。 因此,在最壞的情況下,您可以通過在每次迭代中提前停止一個索引來避免(n-1)**2索引。

這是一個改編的實現:

def optimized_sort(lst):
    lst2 = lst.copy()
    compare = True
    #Creating a variable to store the iteration count
    n = 0
    while compare is True :
        compare=False
        # This time, we walk from index 0 to the last index minus the iteration count
        for i in range(len(lst2) - 1 - n):
            if lst2[i]>lst2[i+1]:
                lst2[i],lst2[i+1] = lst2[i+1], lst2[i]
                compare=True
        # We increment the iteration count
        n += 1
    return lst2

如您所見,優化后的性能確實更高。 排序比較

當然,這種算法仍然表現不佳,主要用於教育目的。

我只是在學習 python,但這對我有用:

def my_sort(lst):
    randHolder = []
    for ele in range(len(lst)):
        mini = min(lst)
        giveIndex = lst.index(mini)
        popped = lst.pop(giveIndex)
        randHolder.append(popped)
    lst = randHolder
    return lst

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM