Hướng dẫn how fast is sort () in python? - sort () trong python nhanh như thế nào?

@Fmark Một số điểm chuẩn của việc thực hiện Python Merge-Sort mà tôi đã viết chống lại Python Quicksorts từ http://rosettacode.org/wiki/sorting_algorithms/quicksort#python và từ câu trả lời hàng đầu.

Show
  1. Kích thước của danh sách và kích thước của các số trong danh sách không liên quan

Hợp nhất sắp xếp chiến thắng, tuy nhiên nó sử dụng tích hợp int () cho sàn

import numpy as np
x = list(np.random.rand(100))


# TEST 1, merge_sort 
def merge(l, p, q, r):
    n1 = q - p + 1
    n2 = r - q
    left = l[p : p + n1]
    right = l[q + 1 : q + 1 + n2]

    i = 0
    j = 0
    k = p
    while k < r + 1:
        if i == n1:
            l[k] = right[j]
            j += 1
        elif j == n2:
            l[k] = left[i]
            i += 1
        elif  left[i] <= right[j]:
            l[k] = left[i]
            i += 1
        else:
            l[k] = right[j]
            j += 1
        k += 1

def _merge_sort(l, p, r):
    if p < r:
        q = int((p + r)/2)
        _merge_sort(l, p, q)
        _merge_sort(l, q+1, r)
        merge(l, p, q, r)

def merge_sort(l):
    _merge_sort(l, 0, len(l)-1)

# TEST 2
def quicksort(array):
    _quicksort(array, 0, len(array) - 1)

def _quicksort(array, start, stop):
    if stop - start > 0:
        pivot, left, right = array[start], start, stop
        while left <= right:
            while array[left] < pivot:
                left += 1
            while array[right] > pivot:
                right -= 1
            if left <= right:
                array[left], array[right] = array[right], array[left]
                left += 1
                right -= 1
        _quicksort(array, start, right)
        _quicksort(array, left, stop)

# TEST 3
def qsort(inlist):
    if inlist == []: 
        return []
    else:
        pivot = inlist[0]
        lesser = qsort([x for x in inlist[1:] if x < pivot])
        greater = qsort([x for x in inlist[1:] if x >= pivot])
        return lesser + [pivot] + greater

def test1():
    merge_sort(x)

def test2():
    quicksort(x)

def test3():
    qsort(x)

if __name__ == '__main__':
    import timeit
    print('merge_sort:', timeit.timeit("test1()", setup="from __main__ import test1, x;", number=10000))
    print('quicksort:', timeit.timeit("test2()", setup="from __main__ import test2, x;", number=10000))
    print('qsort:', timeit.timeit("test3()", setup="from __main__ import test3, x;", number=10000))

Xem, trong lập trình có một khái niệm về sự phức tạp. Thuật toán của bạn - Sắp xếp bong bóng, có độ phức tạp được ghi nhận là

 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
6, có nghĩa là, khi độ dài của danh sách
 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
7 tăng lên, thời gian cần có đa thức theo cấp số nhân (
 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
8). Sắp xếp bong bóng có một trong những phức tạp tồi tệ nhất (danh sách các thuật toán và sự phức tạp của chúng).

Như bạn có thể thấy trong liên kết ở trên, có các thuật toán tốt hơn. Có những cái "tuyến tính" (

 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
9,
 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
7 tỷ lệ thuận với thời gian cần thiết để tính toán với thuật toán này) và sau đó chúng ta có
21ARRAY_LENGTH = 10000
22
23if __name__ == "__main__":
24    # Generate an array of `ARRAY_LENGTH` items consisting
25    # of random integer values between 0 and 999
26    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
27
28    # Call the function using the name of the sorting algorithm
29    # and the array you just created
30    run_sorting_algorithm(algorithm="sorted", array=array)
1. Bạn có thể google một [đồ thị] (https://www.google.pl/search?q=f (x)+%3D+log (x)) của sự phức tạp này, về cơ bản cho thấy điều này -
 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
7 cao hơn là chậm hơn nó phát triển.

Nó là khá hợp lý khi cho rằng

21ARRAY_LENGTH = 10000
22
23if __name__ == "__main__":
24    # Generate an array of `ARRAY_LENGTH` items consisting
25    # of random integer values between 0 and 999
26    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
27
28    # Call the function using the name of the sorting algorithm
29    # and the array you just created
30    run_sorting_algorithm(algorithm="sorted", array=array)
1 là một trong những điều tốt nhất có thể. Hãy thử tìm một thuật toán mà bạn thấy dễ hiểu và thực hiện nó (Wikipedia chủ yếu nên có việc triển khai mã giả)

Chỉnh sửa: Typo

Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự. Xem cùng với hướng dẫn bằng văn bản để hiểu sâu hơn về sự hiểu biết của bạn: Giới thiệu về các thuật toán sắp xếp trong Python This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Introduction to Sorting Algorithms in Python

Chức năng sắp xếp Python có nhanh không? is a basic building block that many other algorithms are built upon. It’s related to several exciting ideas that you’ll see throughout your programming career. Understanding how sorting algorithms in Python work behind the scenes is a fundamental step toward implementing correct and efficient algorithms that solve real-world problems.

Thời gian thực hiện Sắp xếp hợp nhất của bạn so với sắp xếp bong bóng và sắp xếp chèn, việc triển khai Sắp xếp hợp nhất là cực kỳ nhanh, sắp xếp mảng mười nghìn phần tử trong chưa đầy một giây!

  • Sắp xếp () hoặc sắp xếp () nhanh hơn?sorting algorithms in Python work and how they compare under different circumstances
  • Sắp xếp nhanh hơn 13% so với sắp xếp.Python’s built-in sort functionality works behind the scenes
  • Sự phức tạp của thời gian là sắp xếp trong Python?recursion and divide and conquer apply to sorting
  • Sắp xếp. Sắp xếp danh sách Python () đã sử dụng thuật toán TIMSORT kể từ phiên bản 2.3. Thuật toán này có độ phức tạp thời gian chạy của O (N.Logn).Big O notation and Python’s
    21ARRAY_LENGTH = 10000
    22
    23if __name__ == "__main__":
    24    # Generate an array of `ARRAY_LENGTH` items consisting
    25    # of random integer values between 0 and 999
    26    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
    27
    28    # Call the function using the name of the sorting algorithm
    29    # and the array you just created
    30    run_sorting_algorithm(algorithm="sorted", array=array)
    
    4 module

Phương pháp sắp xếp nào là nhanh nhất?

Nếu bạn đã quan sát, độ phức tạp thời gian của QuickSort là O (N logn) trong các trường hợp tốt nhất và trung bình và O (n^2) trong trường hợp xấu nhất. Nhưng vì nó có ưu thế trong các trường hợp trung bình đối với hầu hết các đầu vào, Quicksort thường được coi là thuật toán sắp xếp nhanh nhất trên mạng.

Sắp xếp là một khối xây dựng cơ bản mà nhiều thuật toán khác được xây dựng. Nó có liên quan đến một số ý tưởng thú vị mà bạn sẽ thấy trong suốt sự nghiệp lập trình của mình. Hiểu cách sắp xếp các thuật toán trong Python hoạt động đằng sau hậu trường là một bước cơ bản để thực hiện các thuật toán chính xác và hiệu quả để giải quyết các vấn đề trong thế giới thực.

Trong hướng dẫn này, bạn sẽ học:

  • Các thuật toán sắp xếp khác nhau như thế nào trong Python hoạt động và cách chúng so sánh trong các trường hợp khác nhau Searching for an item on a list works much faster if the list is sorted.

  • Làm thế nào chức năng sắp xếp tích hợp của Python hoạt động ở hậu trường Selecting items from a list based on their relationship to the rest of the items is easier with sorted data. For example, finding the kth-largest or smallest value, or finding the median value of the list, is much easier when the values are in ascending or descending order.

  • Các khái niệm khoa học máy tính khác nhau như đệ quy và phân chia và chinh phục áp dụng như thế nào để phân loại Finding duplicate values on a list can be done very quickly when the list is sorted.

  • Phân phối: Phân tích phân phối tần số của các mục trong danh sách là rất nhanh nếu danh sách được sắp xếp. Ví dụ, tìm phần tử xuất hiện nhất hoặc ít nhất thường là tương đối đơn giản với một danh sách được sắp xếp. Analyzing the frequency distribution of items on a list is very fast if the list is sorted. For example, finding the element that appears most or least often is relatively straightforward with a sorted list.

Từ các ứng dụng thương mại đến nghiên cứu học thuật và ở mọi nơi ở giữa, có vô số cách bạn có thể sử dụng phân loại để tiết kiệm thời gian và công sức của mình.

Thuật toán sắp xếp tích hợp Python

Ngôn ngữ Python, giống như nhiều ngôn ngữ lập trình cấp cao khác, cung cấp khả năng sắp xếp dữ liệu ra khỏi hộp bằng

21ARRAY_LENGTH = 10000
22
23if __name__ == "__main__":
24    # Generate an array of `ARRAY_LENGTH` items consisting
25    # of random integer values between 0 and 999
26    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
27
28    # Call the function using the name of the sorting algorithm
29    # and the array you just created
30    run_sorting_algorithm(algorithm="sorted", array=array)
5. Ở đây, một ví dụ về việc sắp xếp một mảng số nguyên:

>>>

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]

Bạn có thể sử dụng

21ARRAY_LENGTH = 10000
22
23if __name__ == "__main__":
24    # Generate an array of `ARRAY_LENGTH` items consisting
25    # of random integer values between 0 and 999
26    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
27
28    # Call the function using the name of the sorting algorithm
29    # and the array you just created
30    run_sorting_algorithm(algorithm="sorted", array=array)
5 để sắp xếp bất kỳ danh sách nào miễn là các giá trị bên trong có thể so sánh được.

Tầm quan trọng của độ phức tạp thời gian

Hướng dẫn này bao gồm hai cách khác nhau để đo thời gian chạy của các thuật toán sắp xếp:runtime of sorting algorithms:

  1. Đối với quan điểm thực tế, bạn sẽ đo thời gian chạy của các triển khai bằng mô -đun
    21ARRAY_LENGTH = 10000
    22
    23if __name__ == "__main__":
    24    # Generate an array of `ARRAY_LENGTH` items consisting
    25    # of random integer values between 0 and 999
    26    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
    27
    28    # Call the function using the name of the sorting algorithm
    29    # and the array you just created
    30    run_sorting_algorithm(algorithm="sorted", array=array)
    
    4.
  2. Đối với một quan điểm lý thuyết hơn, bạn sẽ đo độ phức tạp thời gian chạy của các thuật toán bằng cách sử dụng ký hiệu O lớn.runtime complexity of the algorithms using Big O notation.

Thời gian mã của bạn

Khi so sánh hai thuật toán sắp xếp trong Python, nó luôn luôn có nhiều thông tin để xem mỗi người mất bao lâu để chạy. Thời gian cụ thể, mỗi thuật toán sẽ được xác định một phần bởi phần cứng của bạn, nhưng bạn vẫn có thể sử dụng thời gian tỷ lệ giữa các lần thực hiện để giúp bạn quyết định triển khai nào hiệu quả hơn về thời gian.

Trong phần này, bạn sẽ tập trung vào một cách thực tế để đo thời gian thực tế để chạy đến các thuật toán sắp xếp của bạn bằng mô -đun

21ARRAY_LENGTH = 10000
22
23if __name__ == "__main__":
24    # Generate an array of `ARRAY_LENGTH` items consisting
25    # of random integer values between 0 and 999
26    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
27
28    # Call the function using the name of the sorting algorithm
29    # and the array you just created
30    run_sorting_algorithm(algorithm="sorted", array=array)
4. Để biết thêm thông tin về các cách khác nhau, bạn có thể thời gian thực hiện mã trong Python, hãy xem các chức năng của Timer Python: Ba cách để theo dõi mã của bạn.

Ở đây, một chức năng bạn có thể sử dụng để thời gian thuật toán của mình:

 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")

Trong ví dụ này,

21ARRAY_LENGTH = 10000
22
23if __name__ == "__main__":
24    # Generate an array of `ARRAY_LENGTH` items consisting
25    # of random integer values between 0 and 999
26    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
27
28    # Call the function using the name of the sorting algorithm
29    # and the array you just created
30    run_sorting_algorithm(algorithm="sorted", array=array)
9 nhận được tên của thuật toán và mảng đầu vào cần được sắp xếp. Ở đây, một lời giải thích từng dòng về cách thức hoạt động:

  • Dòng 8 nhập tên của thuật toán bằng cách sử dụng phép thuật của Python từ F-String. Điều này là để

    $ python sorting.py
    Algorithm: sorted. Minimum execution time: 0.010945824000000007
    
    0 biết nơi gọi thuật toán từ đâu. Lưu ý rằng điều này chỉ cần thiết cho các triển khai tùy chỉnh được sử dụng trong hướng dẫn này. Nếu thuật toán được chỉ định là
    21ARRAY_LENGTH = 10000
    22
    23if __name__ == "__main__":
    24    # Generate an array of `ARRAY_LENGTH` items consisting
    25    # of random integer values between 0 and 999
    26    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
    27
    28    # Call the function using the name of the sorting algorithm
    29    # and the array you just created
    30    run_sorting_algorithm(algorithm="sorted", array=array)
    
    5 tích hợp, thì sẽ không có gì được nhập.
    imports the name of the algorithm using the magic of Python’s f-strings. This is so that
    $ python sorting.py
    Algorithm: sorted. Minimum execution time: 0.010945824000000007
    
    0 knows where to call the algorithm from. Note that this is only necessary for the custom implementations used in this tutorial. If the algorithm specified is the built-in
    21ARRAY_LENGTH = 10000
    22
    23if __name__ == "__main__":
    24    # Generate an array of `ARRAY_LENGTH` items consisting
    25    # of random integer values between 0 and 999
    26    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
    27
    28    # Call the function using the name of the sorting algorithm
    29    # and the array you just created
    30    run_sorting_algorithm(algorithm="sorted", array=array)
    
    5, then nothing will be imported.

  • Dòng 11 chuẩn bị cuộc gọi đến thuật toán với mảng được cung cấp. Đây là tuyên bố sẽ được thực thi và hẹn giờ. prepares the call to the algorithm with the supplied array. This is the statement that will be executed and timed.

  • Dòng 15 gọi

    $ python sorting.py
    Algorithm: sorted. Minimum execution time: 0.010945824000000007
    
    0 với mã thiết lập và câu lệnh. Điều này sẽ gọi thuật toán sắp xếp được chỉ định mười lần, trả về số giây mỗi lần thực hiện. calls
    $ python sorting.py
    Algorithm: sorted. Minimum execution time: 0.010945824000000007
    
    0 with the setup code and the statement. This will call the specified sorting algorithm ten times, returning the number of seconds each one of these executions took.

  • Dòng 19 xác định thời gian ngắn nhất được trả lại và in nó cùng với tên của thuật toán. identifies the shortest time returned and prints it along with the name of the algorithm.

Ở đây, một ví dụ về cách sử dụng

21ARRAY_LENGTH = 10000
22
23if __name__ == "__main__":
24    # Generate an array of `ARRAY_LENGTH` items consisting
25    # of random integer values between 0 and 999
26    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
27
28    # Call the function using the name of the sorting algorithm
29    # and the array you just created
30    run_sorting_algorithm(algorithm="sorted", array=array)
9 để xác định thời gian cần thiết để sắp xếp một mảng gồm mười nghìn giá trị số nguyên bằng cách sử dụng
21ARRAY_LENGTH = 10000
22
23if __name__ == "__main__":
24    # Generate an array of `ARRAY_LENGTH` items consisting
25    # of random integer values between 0 and 999
26    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
27
28    # Call the function using the name of the sorting algorithm
29    # and the array you just created
30    run_sorting_algorithm(algorithm="sorted", array=array)
5:

21ARRAY_LENGTH = 10000
22
23if __name__ == "__main__":
24    # Generate an array of `ARRAY_LENGTH` items consisting
25    # of random integer values between 0 and 999
26    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
27
28    # Call the function using the name of the sorting algorithm
29    # and the array you just created
30    run_sorting_algorithm(algorithm="sorted", array=array)

Nếu bạn lưu mã trên trong tệp

$ python sorting.py
Algorithm: sorted. Minimum execution time: 0.010945824000000007
5, thì bạn có thể chạy nó từ thiết bị đầu cuối và xem đầu ra của nó:

$ python sorting.py
Algorithm: sorted. Minimum execution time: 0.010945824000000007

Hãy nhớ rằng thời gian tính bằng giây của mỗi thử nghiệm phụ thuộc một phần vào phần cứng bạn sử dụng, do đó, bạn có thể sẽ thấy kết quả hơi khác nhau khi chạy mã.

Đo lường hiệu quả với ký hiệu O lớn

Thời gian cụ thể mà một thuật toán cần để chạy isn không đủ thông tin để có được bức tranh đầy đủ về độ phức tạp của thời gian của nó. Để giải quyết vấn đề này, bạn có thể sử dụng ký hiệu Big O (phát âm là OH OH). Big O thường được sử dụng để so sánh các triển khai khác nhau và quyết định xem cái nào là hiệu quả nhất, bỏ qua các chi tiết không cần thiết và tập trung vào những gì quan trọng nhất trong thời gian chạy của thuật toán.time complexity. To solve this problem, you can use Big O (pronounced “big oh”) notation. Big O is often used to compare different implementations and decide which one is the most efficient, skipping unnecessary details and focusing on what’s most important in the runtime of an algorithm.

Thời gian tính bằng giây cần thiết để chạy các thuật toán khác nhau có thể bị ảnh hưởng bởi một số yếu tố không liên quan, bao gồm tốc độ bộ xử lý hoặc bộ nhớ có sẵn. Big O, mặt khác, cung cấp một nền tảng để thể hiện độ phức tạp thời gian chạy về mặt bất khả tri phần cứng. Với Big O, bạn thể hiện sự phức tạp về mức độ thời gian chạy của thuật toán của bạn phát triển nhanh như thế nào so với kích thước của đầu vào, đặc biệt là khi đầu vào phát triển tùy ý lớn.

Giả sử rằng N là kích thước của đầu vào cho một thuật toán, ký hiệu O lớn đại diện cho mối quan hệ giữa N và số bước mà thuật toán thực hiện để tìm giải pháp. Big O sử dụng một chữ cái viết hoa, sau đó là mối quan hệ này bên trong ngoặc đơn. Ví dụ: O (n) đại diện cho các thuật toán thực hiện một số bước tỷ lệ thuận với kích thước của đầu vào của chúng.O(n) represents algorithms that execute a number of steps proportional to the size of their input.

Mặc dù hướng dẫn này sẽ không đi sâu vào các chi tiết về ký hiệu Big O, nhưng đây là năm ví dụ về độ phức tạp thời gian chạy của các thuật toán khác nhau:

Lớn oSự phức tạpSự mô tả
O (1)không thay đổiThời gian chạy là không đổi bất kể kích thước của đầu vào. Tìm một phần tử trong bảng băm là một ví dụ về một hoạt động có thể được thực hiện trong thời gian không đổi.constant time.
Trên)tuyến tínhThời gian chạy phát triển tuyến tính với kích thước của đầu vào. Hàm kiểm tra một điều kiện trên mọi mục của danh sách là một ví dụ về thuật toán O (n).
O (n2)bậc haiThời gian chạy là một hàm bậc hai của kích thước của đầu vào. Một triển khai ngây thơ của việc tìm kiếm các giá trị trùng lặp trong một danh sách, trong đó mỗi mục phải được kiểm tra hai lần, là một ví dụ về thuật toán bậc hai.
O (2n)số mũThời gian chạy phát triển theo cấp số nhân với kích thước của đầu vào. Các thuật toán này được coi là cực kỳ kém hiệu quả. Một ví dụ về thuật toán theo cấp số nhân là vấn đề ba màu.
O (log n)logaritThời gian chạy phát triển tuyến tính trong khi kích thước của đầu vào tăng theo cấp số nhân. Ví dụ: nếu mất một giây để xử lý một nghìn yếu tố, thì sẽ mất hai giây để xử lý mười nghìn, ba giây để xử lý một trăm nghìn, v.v. Tìm kiếm nhị phân là một ví dụ về thuật toán thời gian chạy logarit.

Hướng dẫn này bao gồm độ phức tạp thời gian chạy O của từng thuật toán sắp xếp được thảo luận. Nó cũng bao gồm một lời giải thích ngắn gọn về cách xác định thời gian chạy trên từng trường hợp cụ thể. Điều này sẽ cho bạn hiểu rõ hơn về cách bắt đầu sử dụng Big O để phân loại các thuật toán khác.

Thuật toán sắp xếp bong bóng trong python

Sắp xếp bong bóng là một trong những thuật toán sắp xếp đơn giản nhất. Tên của nó xuất phát từ cách thức hoạt động của thuật toán: với mỗi lần vượt qua mới, yếu tố lớn nhất trong danh sách Bong bóng bong bóng lên trên vị trí chính xác của nó. is one of the most straightforward sorting algorithms. Its name comes from the way the algorithm works: With every new pass, the largest element in the list “bubbles up” toward its correct position.

Sắp xếp bong bóng bao gồm thực hiện nhiều đường chuyền qua một danh sách, so sánh từng yếu tố một và hoán đổi các mục liền kề không có thứ tự.

Thực hiện phân loại bong bóng trong Python

Ở đây, một việc thực hiện thuật toán sắp xếp bong bóng trong Python:

 1def bubble_sort(array):
 2    n = len(array)
 3
 4    for i in range(n):
 5        # Create a flag that will allow the function to
 6        # terminate early if there's nothing left to sort
 7        already_sorted = True
 8
 9        # Start looking at each item of the list one by one,
10        # comparing it with its adjacent value. With each
11        # iteration, the portion of the array that you look at
12        # shrinks because the remaining items have already been
13        # sorted.
14        for j in range(n - i - 1):
15            if array[j] > array[j + 1]:
16                # If the item you're looking at is greater than its
17                # adjacent value, then swap them
18                array[j], array[j + 1] = array[j + 1], array[j]
19
20                # Since you had to swap two elements,
21                # set the `already_sorted` flag to `False` so the
22                # algorithm doesn't finish prematurely
23                already_sorted = False
24
25        # If there were no swaps during the last iteration,
26        # the array is already sorted, and you can terminate
27        if already_sorted:
28            break
29
30    return array

Vì việc triển khai này sắp xếp mảng theo thứ tự tăng dần, mỗi bước bong bóng, thành phần lớn nhất đến cuối mảng. Điều này có nghĩa là mỗi lần lặp có ít các bước hơn so với lần lặp trước vì một phần lớn hơn của mảng được sắp xếp.

Các vòng lặp trong dòng 4 và 10 xác định cách thuật toán chạy qua danh sách. Lưu ý cách

$ python sorting.py
Algorithm: sorted. Minimum execution time: 0.010945824000000007
6 ban đầu đi từ phần tử đầu tiên trong danh sách đến phần tử ngay trước phần cuối. Trong lần lặp thứ hai,
$ python sorting.py
Algorithm: sorted. Minimum execution time: 0.010945824000000007
6 chạy cho đến hai mục từ cuối cùng, sau đó ba mục từ cuối cùng, v.v. Vào cuối mỗi lần lặp, phần cuối của danh sách sẽ được sắp xếp.lines 4 and 10 determine the way the algorithm runs through the list. Notice how
$ python sorting.py
Algorithm: sorted. Minimum execution time: 0.010945824000000007
6 initially goes from the first element in the list to the element immediately before the last. During the second iteration,
$ python sorting.py
Algorithm: sorted. Minimum execution time: 0.010945824000000007
6 runs until two items from the last, then three items from the last, and so on. At the end of each iteration, the end portion of the list will be sorted.

Khi các vòng lặp tiến triển, dòng 15 so sánh từng phần tử với giá trị liền kề của nó và dòng 18 hoán đổi chúng nếu chúng theo thứ tự không chính xác. Điều này đảm bảo một danh sách được sắp xếp ở cuối hàm.line 15 compares each element with its adjacent value, and line 18 swaps them if they are in the incorrect order. This ensures a sorted list at the end of the function.

Để phân tích chính xác cách thức hoạt động của thuật toán, hãy xem xét một danh sách với các giá trị

$ python sorting.py
Algorithm: sorted. Minimum execution time: 0.010945824000000007
8. Giả sử bạn sử dụng
$ python sorting.py
Algorithm: sorted. Minimum execution time: 0.010945824000000007
9 từ trên cao. Dưới đây, một con số minh họa cho mảng trông như thế nào ở mỗi lần lặp của thuật toán:

Hướng dẫn how fast is sort () in python? - sort () trong python nhanh như thế nào?
Quá trình sắp xếp bong bóng

Bây giờ hãy xem xét từng bước về những gì mà xảy ra với mảng khi thuật toán tiến triển:

  1. Mã bắt đầu bằng cách so sánh phần tử đầu tiên,

     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    0, với phần tử liền kề của nó,
     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    1. Kể từ
     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    2, các giá trị được hoán đổi, dẫn đến thứ tự sau:
     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    3.

  2. Thuật toán sau đó so sánh phần tử thứ hai,

     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    0, với phần tử liền kề của nó,
     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    5. Kể từ
     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    6, các giá trị được hoán đổi, dẫn đến thứ tự sau:
     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    7.

  3. Tiếp theo, thuật toán so sánh phần tử thứ ba,

     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    0, với phần tử liền kề của nó,
     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    9. Vì
     1if __name__ == "__main__":
     2    # Generate an array of `ARRAY_LENGTH` items consisting
     3    # of random integer values between 0 and 999
     4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
     5
     6    # Call the function using the name of the sorting algorithm
     7    # and the array you just created
     8    run_sorting_algorithm(algorithm="bubble_sort", array=array)
    
    0, nó cũng hoán đổi các giá trị, dẫn đến thứ tự sau:
     1if __name__ == "__main__":
     2    # Generate an array of `ARRAY_LENGTH` items consisting
     3    # of random integer values between 0 and 999
     4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
     5
     6    # Call the function using the name of the sorting algorithm
     7    # and the array you just created
     8    run_sorting_algorithm(algorithm="bubble_sort", array=array)
    
    1.

  4. Cuối cùng, thuật toán so sánh phần tử thứ tư,

     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    0, với phần tử liền kề của nó,
     1if __name__ == "__main__":
     2    # Generate an array of `ARRAY_LENGTH` items consisting
     3    # of random integer values between 0 and 999
     4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
     5
     6    # Call the function using the name of the sorting algorithm
     7    # and the array you just created
     8    run_sorting_algorithm(algorithm="bubble_sort", array=array)
    
    3 và cũng hoán đổi chúng, dẫn đến
     1if __name__ == "__main__":
     2    # Generate an array of `ARRAY_LENGTH` items consisting
     3    # of random integer values between 0 and 999
     4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
     5
     6    # Call the function using the name of the sorting algorithm
     7    # and the array you just created
     8    run_sorting_algorithm(algorithm="bubble_sort", array=array)
    
    4. Tại thời điểm này, thuật toán đã hoàn thành thẻ đầu tiên thông qua danh sách (
     1if __name__ == "__main__":
     2    # Generate an array of `ARRAY_LENGTH` items consisting
     3    # of random integer values between 0 and 999
     4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
     5
     6    # Call the function using the name of the sorting algorithm
     7    # and the array you just created
     8    run_sorting_algorithm(algorithm="bubble_sort", array=array)
    
    5). Lưu ý cách giá trị
     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    0 sủi bọt từ vị trí ban đầu của nó đến vị trí chính xác của nó ở cuối danh sách.

  5. Đường chuyền thứ hai (

     1if __name__ == "__main__":
     2    # Generate an array of `ARRAY_LENGTH` items consisting
     3    # of random integer values between 0 and 999
     4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
     5
     6    # Call the function using the name of the sorting algorithm
     7    # and the array you just created
     8    run_sorting_algorithm(algorithm="bubble_sort", array=array)
    
    7) tính đến phần tử cuối cùng của danh sách đã được định vị và tập trung vào bốn yếu tố còn lại,
     1if __name__ == "__main__":
     2    # Generate an array of `ARRAY_LENGTH` items consisting
     3    # of random integer values between 0 and 999
     4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
     5
     6    # Call the function using the name of the sorting algorithm
     7    # and the array you just created
     8    run_sorting_algorithm(algorithm="bubble_sort", array=array)
    
    8. Vào cuối vượt qua này, giá trị
     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    5 tìm thấy vị trí chính xác của nó. Lần thứ ba vượt qua danh sách vị trí giá trị
     1if __name__ == "__main__":
     2    # Generate an array of `ARRAY_LENGTH` items consisting
     3    # of random integer values between 0 and 999
     4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
     5
     6    # Call the function using the name of the sorting algorithm
     7    # and the array you just created
     8    run_sorting_algorithm(algorithm="bubble_sort", array=array)
    
    3, v.v. cho đến khi danh sách được sắp xếp.

Đo lường độ phức tạp thời gian chạy của Bubble sắp xếp

Việc thực hiện phân loại bong bóng của bạn bao gồm hai vòng

$ python sorting.py
Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
1 lồng nhau trong đó thuật toán thực hiện so sánh n - 1, sau đó so sánh n - 2, v.v. cho đến khi so sánh cuối cùng được thực hiện. Điều này có tổng cộng (n - 1) + (n - 2) + (n - 3) + + + 2 + 1 = n (n -1)/2 so sánh, cũng có thể được viết là ½n2 - ½n.

Bạn đã học được trước đó rằng Big O tập trung vào cách thời gian chạy phát triển so với kích thước của đầu vào. Điều đó có nghĩa là, để biến phương trình trên thành độ phức tạp o lớn của thuật toán, bạn cần loại bỏ các hằng số vì chúng không thay đổi với kích thước đầu vào.

Làm như vậy đơn giản hóa ký hiệu thành N2 - n. Vì N2 phát triển nhanh hơn nhiều so với N, nên thuật ngữ cuối cùng này cũng có thể được giảm, để lại sự sắp xếp bong bóng với độ phức tạp trung bình và trường hợp xấu nhất của O (N2).O(n2).

Trong trường hợp thuật toán nhận được một mảng đã được sắp xếp và giả sử việc triển khai bao gồm tối ưu hóa cờ ____72 được giải thích trước khi độ phức tạp thời gian chạy sẽ giảm xuống (n) tốt hơn nhiều vì thuật toán sẽ không cần truy cập vào bất kỳ phần tử nào hơn là nhiều hơn Một lần.

O (n), sau đó, là độ phức tạp thời gian chạy trong trường hợp tốt nhất của loại bong bóng. Nhưng hãy nhớ rằng các trường hợp tốt nhất là một ngoại lệ và bạn nên tập trung vào trường hợp trung bình khi so sánh các thuật toán khác nhau.

Thời gian thực hiện sắp xếp bong bóng của bạn

Sử dụng

21ARRAY_LENGTH = 10000
22
23if __name__ == "__main__":
24    # Generate an array of `ARRAY_LENGTH` items consisting
25    # of random integer values between 0 and 999
26    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
27
28    # Call the function using the name of the sorting algorithm
29    # and the array you just created
30    run_sorting_algorithm(algorithm="sorted", array=array)
9 của bạn từ trước đó trong hướng dẫn này, ở đây, thời gian sắp xếp bong bóng để xử lý một mảng với mười nghìn mặt hàng. Dòng 8 thay thế tên của thuật toán và mọi thứ khác vẫn giữ nguyên:Line 8 replaces the name of the algorithm and everything else stays the same:

 1if __name__ == "__main__":
 2    # Generate an array of `ARRAY_LENGTH` items consisting
 3    # of random integer values between 0 and 999
 4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
 5
 6    # Call the function using the name of the sorting algorithm
 7    # and the array you just created
 8    run_sorting_algorithm(algorithm="bubble_sort", array=array)

Bây giờ bạn có thể chạy tập lệnh để có thời gian thực hiện là

$ python sorting.py
Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
4:

$ python sorting.py
Algorithm: bubble_sort. Minimum execution time: 73.21720498399998

Phải mất

$ python sorting.py
Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
5 giây để sắp xếp mảng với mười nghìn yếu tố. Điều này thể hiện sự thực hiện nhanh nhất trong số mười lần lặp lại mà
21ARRAY_LENGTH = 10000
22
23if __name__ == "__main__":
24    # Generate an array of `ARRAY_LENGTH` items consisting
25    # of random integer values between 0 and 999
26    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
27
28    # Call the function using the name of the sorting algorithm
29    # and the array you just created
30    run_sorting_algorithm(algorithm="sorted", array=array)
9 chạy. Thực hiện tập lệnh này nhiều lần sẽ tạo ra kết quả tương tự.

Phân tích điểm mạnh và điểm yếu của loại bong bóng

Ưu điểm chính của thuật toán sắp xếp bong bóng là sự đơn giản của nó. Nó là đơn giản để cả thực hiện và hiểu. Đây có lẽ là lý do chính tại sao hầu hết các khóa học khoa học máy tính giới thiệu chủ đề sắp xếp bằng cách sử dụng loại bong bóng.simplicity. It is straightforward to both implement and understand. This is probably the main reason why most computer science courses introduce the topic of sorting using bubble sort.

Như bạn đã thấy trước đây, nhược điểm của loại bong bóng là nó chậm, với độ phức tạp thời gian chạy của O (N2). Thật không may, điều này quy định nó như một ứng cử viên thực tế để sắp xếp các mảng lớn.slow, with a runtime complexity of O(n2). Unfortunately, this rules it out as a practical candidate for sorting large arrays.

Thuật toán loại chèn trong python

Giống như sắp xếp bong bóng, thuật toán loại chèn rất đơn giản để thực hiện và hiểu. Nhưng không giống như Sắp xếp bong bóng, nó xây dựng danh sách được sắp xếp một phần tử tại một thời điểm bằng cách so sánh từng mục với phần còn lại của danh sách và chèn nó vào vị trí chính xác của nó. Quy trình chèn này của người Viking này cung cấp cho thuật toán tên của nó.insertion sort algorithm is straightforward to implement and understand. But unlike bubble sort, it builds the sorted list one element at a time by comparing each item with the rest of the list and inserting it into its correct position. This “insertion” procedure gives the algorithm its name.

Một sự tương tự tuyệt vời để giải thích loại chèn là cách bạn sắp xếp một bộ bài. Hãy tưởng tượng rằng bạn đang cầm một nhóm thẻ trong tay và bạn muốn sắp xếp chúng theo thứ tự. Bạn bắt đầu bằng cách so sánh một thẻ duy nhất từng bước với phần còn lại của thẻ cho đến khi bạn tìm thấy vị trí chính xác của nó. Tại thời điểm đó, bạn đã chèn thẻ ở vị trí chính xác và bắt đầu lại với một thẻ mới, lặp lại cho đến khi tất cả các thẻ trong tay bạn được sắp xếp.

Thực hiện sắp xếp chèn trong Python

Thuật toán sắp xếp chèn hoạt động chính xác giống như ví dụ với bộ bài của thẻ. Ở đây, việc thực hiện trong Python:

 1def insertion_sort(array):
 2    # Loop from the second element of the array until
 3    # the last element
 4    for i in range(1, len(array)):
 5        # This is the element we want to position in its
 6        # correct place
 7        key_item = array[i]
 8
 9        # Initialize the variable that will be used to
10        # find the correct position of the element referenced
11        # by `key_item`
12        j = i - 1
13
14        # Run through the list of items (the left
15        # portion of the array) and find the correct position
16        # of the element referenced by `key_item`. Do this only
17        # if `key_item` is smaller than its adjacent values.
18        while j >= 0 and array[j] > key_item:
19            # Shift the value one position to the left
20            # and reposition j to point to the next element
21            # (from right to left)
22            array[j + 1] = array[j]
23            j -= 1
24
25        # When you finish shifting the elements, you can position
26        # `key_item` in its correct location
27        array[j + 1] = key_item
28
29    return array

Không giống như sắp xếp bong bóng, việc triển khai loại chèn này xây dựng danh sách được sắp xếp bằng cách đẩy các mục nhỏ hơn sang trái. Hãy cùng phá vỡ dòng

$ python sorting.py
Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
7 từng dòng:

  • Dòng 4 thiết lập vòng lặp xác định

    $ python sorting.py
    Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
    
    8 rằng hàm sẽ định vị trong mỗi lần lặp. Lưu ý rằng vòng lặp bắt đầu với mục thứ hai trong danh sách và đi đến mục cuối cùng. sets up the loop that determines the
    $ python sorting.py
    Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
    
    8 that the function will position during each iteration. Notice that the loop starts with the second item on the list and goes all the way to the last item.

  • Dòng 7 Khởi tạo

    $ python sorting.py
    Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
    
    8 với mục mà chức năng đang cố gắng đặt. initializes
    $ python sorting.py
    Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
    
    8 with the item that the function is trying to place.

  • Dòng 12 Khởi tạo một biến sẽ chỉ liên tiếp đến từng phần tử ở bên trái của

     1def insertion_sort(array):
     2    # Loop from the second element of the array until
     3    # the last element
     4    for i in range(1, len(array)):
     5        # This is the element we want to position in its
     6        # correct place
     7        key_item = array[i]
     8
     9        # Initialize the variable that will be used to
    10        # find the correct position of the element referenced
    11        # by `key_item`
    12        j = i - 1
    13
    14        # Run through the list of items (the left
    15        # portion of the array) and find the correct position
    16        # of the element referenced by `key_item`. Do this only
    17        # if `key_item` is smaller than its adjacent values.
    18        while j >= 0 and array[j] > key_item:
    19            # Shift the value one position to the left
    20            # and reposition j to point to the next element
    21            # (from right to left)
    22            array[j + 1] = array[j]
    23            j -= 1
    24
    25        # When you finish shifting the elements, you can position
    26        # `key_item` in its correct location
    27        array[j + 1] = key_item
    28
    29    return array
    
    0. Đây là những yếu tố sẽ được liên tiếp so với
    $ python sorting.py
    Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
    
    8.
    initializes a variable that will consecutively point to each element to the left of
     1def insertion_sort(array):
     2    # Loop from the second element of the array until
     3    # the last element
     4    for i in range(1, len(array)):
     5        # This is the element we want to position in its
     6        # correct place
     7        key_item = array[i]
     8
     9        # Initialize the variable that will be used to
    10        # find the correct position of the element referenced
    11        # by `key_item`
    12        j = i - 1
    13
    14        # Run through the list of items (the left
    15        # portion of the array) and find the correct position
    16        # of the element referenced by `key_item`. Do this only
    17        # if `key_item` is smaller than its adjacent values.
    18        while j >= 0 and array[j] > key_item:
    19            # Shift the value one position to the left
    20            # and reposition j to point to the next element
    21            # (from right to left)
    22            array[j + 1] = array[j]
    23            j -= 1
    24
    25        # When you finish shifting the elements, you can position
    26        # `key_item` in its correct location
    27        array[j + 1] = key_item
    28
    29    return array
    
    0. These are the elements that will be consecutively compared with
    $ python sorting.py
    Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
    
    8.

  • Dòng 18 so sánh

    $ python sorting.py
    Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
    
    8 với mỗi giá trị bên trái bằng cách sử dụng vòng lặp
     1def insertion_sort(array):
     2    # Loop from the second element of the array until
     3    # the last element
     4    for i in range(1, len(array)):
     5        # This is the element we want to position in its
     6        # correct place
     7        key_item = array[i]
     8
     9        # Initialize the variable that will be used to
    10        # find the correct position of the element referenced
    11        # by `key_item`
    12        j = i - 1
    13
    14        # Run through the list of items (the left
    15        # portion of the array) and find the correct position
    16        # of the element referenced by `key_item`. Do this only
    17        # if `key_item` is smaller than its adjacent values.
    18        while j >= 0 and array[j] > key_item:
    19            # Shift the value one position to the left
    20            # and reposition j to point to the next element
    21            # (from right to left)
    22            array[j + 1] = array[j]
    23            j -= 1
    24
    25        # When you finish shifting the elements, you can position
    26        # `key_item` in its correct location
    27        array[j + 1] = key_item
    28
    29    return array
    
    3, thay đổi các yếu tố để nhường chỗ cho việc đặt
    $ python sorting.py
    Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
    
    8.
    compares
    $ python sorting.py
    Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
    
    8 with each value to its left using a
     1def insertion_sort(array):
     2    # Loop from the second element of the array until
     3    # the last element
     4    for i in range(1, len(array)):
     5        # This is the element we want to position in its
     6        # correct place
     7        key_item = array[i]
     8
     9        # Initialize the variable that will be used to
    10        # find the correct position of the element referenced
    11        # by `key_item`
    12        j = i - 1
    13
    14        # Run through the list of items (the left
    15        # portion of the array) and find the correct position
    16        # of the element referenced by `key_item`. Do this only
    17        # if `key_item` is smaller than its adjacent values.
    18        while j >= 0 and array[j] > key_item:
    19            # Shift the value one position to the left
    20            # and reposition j to point to the next element
    21            # (from right to left)
    22            array[j + 1] = array[j]
    23            j -= 1
    24
    25        # When you finish shifting the elements, you can position
    26        # `key_item` in its correct location
    27        array[j + 1] = key_item
    28
    29    return array
    
    3 loop, shifting the elements to make room to place
    $ python sorting.py
    Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
    
    8.

  • Dòng 27 Vị trí

    $ python sorting.py
    Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
    
    8 ở vị trí chính xác của nó sau khi thuật toán chuyển tất cả các giá trị lớn hơn sang phải. positions
    $ python sorting.py
    Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
    
    8 in its correct place after the algorithm shifts all the larger values to the right.

Dưới đây, một con số minh họa các lần lặp khác nhau của thuật toán khi sắp xếp mảng

$ python sorting.py
Algorithm: sorted. Minimum execution time: 0.010945824000000007
8:

Hướng dẫn how fast is sort () in python? - sort () trong python nhanh như thế nào?
Quy trình sắp xếp chèn

Bây giờ ở đây, một bản tóm tắt các bước của thuật toán khi sắp xếp mảng:

  1. Thuật toán bắt đầu với

     1def insertion_sort(array):
     2    # Loop from the second element of the array until
     3    # the last element
     4    for i in range(1, len(array)):
     5        # This is the element we want to position in its
     6        # correct place
     7        key_item = array[i]
     8
     9        # Initialize the variable that will be used to
    10        # find the correct position of the element referenced
    11        # by `key_item`
    12        j = i - 1
    13
    14        # Run through the list of items (the left
    15        # portion of the array) and find the correct position
    16        # of the element referenced by `key_item`. Do this only
    17        # if `key_item` is smaller than its adjacent values.
    18        while j >= 0 and array[j] > key_item:
    19            # Shift the value one position to the left
    20            # and reposition j to point to the next element
    21            # (from right to left)
    22            array[j + 1] = array[j]
    23            j -= 1
    24
    25        # When you finish shifting the elements, you can position
    26        # `key_item` in its correct location
    27        array[j + 1] = key_item
    28
    29    return array
    
    7 và đi qua Subarray sang trái để tìm vị trí chính xác cho nó. Trong trường hợp này, Subarray là
     1def insertion_sort(array):
     2    # Loop from the second element of the array until
     3    # the last element
     4    for i in range(1, len(array)):
     5        # This is the element we want to position in its
     6        # correct place
     7        key_item = array[i]
     8
     9        # Initialize the variable that will be used to
    10        # find the correct position of the element referenced
    11        # by `key_item`
    12        j = i - 1
    13
    14        # Run through the list of items (the left
    15        # portion of the array) and find the correct position
    16        # of the element referenced by `key_item`. Do this only
    17        # if `key_item` is smaller than its adjacent values.
    18        while j >= 0 and array[j] > key_item:
    19            # Shift the value one position to the left
    20            # and reposition j to point to the next element
    21            # (from right to left)
    22            array[j + 1] = array[j]
    23            j -= 1
    24
    25        # When you finish shifting the elements, you can position
    26        # `key_item` in its correct location
    27        array[j + 1] = key_item
    28
    29    return array
    
    8.

  2. Kể từ

     1def insertion_sort(array):
     2    # Loop from the second element of the array until
     3    # the last element
     4    for i in range(1, len(array)):
     5        # This is the element we want to position in its
     6        # correct place
     7        key_item = array[i]
     8
     9        # Initialize the variable that will be used to
    10        # find the correct position of the element referenced
    11        # by `key_item`
    12        j = i - 1
    13
    14        # Run through the list of items (the left
    15        # portion of the array) and find the correct position
    16        # of the element referenced by `key_item`. Do this only
    17        # if `key_item` is smaller than its adjacent values.
    18        while j >= 0 and array[j] > key_item:
    19            # Shift the value one position to the left
    20            # and reposition j to point to the next element
    21            # (from right to left)
    22            array[j + 1] = array[j]
    23            j -= 1
    24
    25        # When you finish shifting the elements, you can position
    26        # `key_item` in its correct location
    27        array[j + 1] = key_item
    28
    29    return array
    
    9, thuật toán chuyển phần tử
     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    0 một vị trí sang phải. Mảng kết quả tại thời điểm này là
     1if __name__ == "__main__":
     2    # Generate an array of `ARRAY_LENGTH` items consisting
     3    # of random integer values between 0 and 999
     4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
     5
     6    # Call the function using the name of the sorting algorithm
     7    # and the array we just created
     8    run_sorting_algorithm(algorithm="insertion_sort", array=array)
    
    1.

  3. Vì không có thêm các yếu tố nào trong Subarray,

    $ python sorting.py
    Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
    
    8 hiện được đặt ở vị trí mới và mảng cuối cùng là
     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    3.

  4. Đường chuyền thứ hai bắt đầu với

     1if __name__ == "__main__":
     2    # Generate an array of `ARRAY_LENGTH` items consisting
     3    # of random integer values between 0 and 999
     4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
     5
     6    # Call the function using the name of the sorting algorithm
     7    # and the array we just created
     8    run_sorting_algorithm(algorithm="insertion_sort", array=array)
    
    4 và đi qua Subarray nằm bên trái, trong trường hợp này là
     1if __name__ == "__main__":
     2    # Generate an array of `ARRAY_LENGTH` items consisting
     3    # of random integer values between 0 and 999
     4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
     5
     6    # Call the function using the name of the sorting algorithm
     7    # and the array we just created
     8    run_sorting_algorithm(algorithm="insertion_sort", array=array)
    
    5.

  5. Kể từ

     1if __name__ == "__main__":
     2    # Generate an array of `ARRAY_LENGTH` items consisting
     3    # of random integer values between 0 and 999
     4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
     5
     6    # Call the function using the name of the sorting algorithm
     7    # and the array we just created
     8    run_sorting_algorithm(algorithm="insertion_sort", array=array)
    
    6, thuật toán chuyển 8 sang phải. Mảng kết quả tại thời điểm này là
     1if __name__ == "__main__":
     2    # Generate an array of `ARRAY_LENGTH` items consisting
     3    # of random integer values between 0 and 999
     4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
     5
     6    # Call the function using the name of the sorting algorithm
     7    # and the array we just created
     8    run_sorting_algorithm(algorithm="insertion_sort", array=array)
    
    7.

  6. Kể từ

     1if __name__ == "__main__":
     2    # Generate an array of `ARRAY_LENGTH` items consisting
     3    # of random integer values between 0 and 999
     4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
     5
     6    # Call the function using the name of the sorting algorithm
     7    # and the array we just created
     8    run_sorting_algorithm(algorithm="insertion_sort", array=array)
    
    8, thuật toán không cần phải tiếp tục đi qua Subarray, vì vậy nó định vị
    $ python sorting.py
    Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
    
    8 và kết thúc đường chuyền thứ hai. Tại thời điểm này, mảng kết quả là
     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    7.

  7. Lần thứ ba thông qua danh sách đặt phần tử

     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    9 ở vị trí chính xác của nó và phần tử thứ tư Pass đặt phần tử
     1if __name__ == "__main__":
     2    # Generate an array of `ARRAY_LENGTH` items consisting
     3    # of random integer values between 0 and 999
     4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
     5
     6    # Call the function using the name of the sorting algorithm
     7    # and the array you just created
     8    run_sorting_algorithm(algorithm="bubble_sort", array=array)
    
    3 ở đúng vị trí, để lại mảng được sắp xếp.

Đo lường chèn sắp xếp độ phức tạp thời gian chạy o lớn

Tương tự như triển khai Sắp xếp bong bóng của bạn, thuật toán sắp xếp chèn có một vài vòng lặp lồng nhau đi qua danh sách. Vòng bên trong khá hiệu quả vì nó chỉ đi qua danh sách cho đến khi nó tìm thấy vị trí chính xác của một phần tử. Điều đó nói rằng, thuật toán vẫn có độ phức tạp thời gian chạy O (N2) trên trường hợp trung bình.O(n2) runtime complexity on the average case.

Trường hợp xấu nhất xảy ra khi mảng được cung cấp được sắp xếp theo thứ tự ngược lại. Trong trường hợp này, vòng lặp bên trong phải thực hiện mọi so sánh để đặt mọi yếu tố vào vị trí chính xác của nó. Điều này vẫn cung cấp cho bạn độ phức tạp thời gian chạy O (N2).

Trường hợp tốt nhất xảy ra khi mảng được cung cấp đã được sắp xếp. Ở đây, vòng lặp bên trong không bao giờ được thực hiện, dẫn đến độ phức tạp thời gian chạy O (n), giống như trường hợp tốt nhất của loại bong bóng.

Mặc dù sắp xếp bong bóng và sắp xếp chèn có cùng độ phức tạp thời gian chạy O lớn, nhưng trong thực tế, loại chèn có hiệu quả hơn đáng kể so với sắp xếp bong bóng. Nếu bạn nhìn vào việc triển khai cả hai thuật toán, thì bạn có thể thấy cách sắp xếp chèn phải thực hiện ít so sánh hơn để sắp xếp danh sách.

Thời gian thực hiện sắp xếp chèn của bạn

Để chứng minh khẳng định rằng loại chèn hiệu quả hơn so với sắp xếp bong bóng, bạn có thể theo thời gian thuật toán loại chèn và so sánh nó với kết quả sắp xếp bong bóng. Để làm điều này, bạn chỉ cần thay thế cuộc gọi đến

21ARRAY_LENGTH = 10000
22
23if __name__ == "__main__":
24    # Generate an array of `ARRAY_LENGTH` items consisting
25    # of random integer values between 0 and 999
26    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
27
28    # Call the function using the name of the sorting algorithm
29    # and the array you just created
30    run_sorting_algorithm(algorithm="sorted", array=array)
9 bằng tên của việc thực hiện loại chèn của bạn:

 1if __name__ == "__main__":
 2    # Generate an array of `ARRAY_LENGTH` items consisting
 3    # of random integer values between 0 and 999
 4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
 5
 6    # Call the function using the name of the sorting algorithm
 7    # and the array we just created
 8    run_sorting_algorithm(algorithm="insertion_sort", array=array)

Bạn có thể thực thi tập lệnh như trước:

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
0

Lưu ý cách triển khai sắp xếp chèn mất khoảng

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
04 ít giây so với triển khai sắp xếp bong bóng để sắp xếp cùng một mảng. Mặc dù chúng là cả hai thuật toán O (N2), sắp xếp chèn hiệu quả hơn.

Phân tích điểm mạnh và điểm yếu của sự sắp xếp chèn

Giống như sắp xếp bong bóng, thuật toán loại chèn rất không phức tạp để thực hiện. Mặc dù sắp xếp chèn là thuật toán O (N2), nhưng nó cũng hiệu quả hơn nhiều trong thực tế so với các triển khai bậc hai khác như sắp xếp bong bóng.

Có nhiều thuật toán mạnh mẽ hơn, bao gồm cả Merge sắp xếp và Quicksort, nhưng các triển khai này là đệ quy và thường không đánh bại sắp xếp chèn khi làm việc trên các danh sách nhỏ. Một số triển khai QuickSort thậm chí sử dụng chèn sắp xếp nội bộ nếu danh sách đủ nhỏ để cung cấp triển khai tổng thể nhanh hơn. TimSort cũng sử dụng chèn sắp xếp bên trong để sắp xếp các phần nhỏ của mảng đầu vào.Timsort also uses insertion sort internally to sort small portions of the input array.

Điều đó nói rằng, loại chèn là không thực tế cho các mảng lớn, mở ra cánh cửa cho các thuật toán có thể mở rộng theo những cách hiệu quả hơn.

Thuật toán sắp xếp hợp nhất trong Python

Sắp xếp hợp nhất là một thuật toán sắp xếp rất hiệu quả. Nó dựa trên cách tiếp cận phân chia và chinh phục, một kỹ thuật thuật toán mạnh mẽ được sử dụng để giải quyết các vấn đề phức tạp. is a very efficient sorting algorithm. It’s based on the divide-and-conquer approach, a powerful algorithmic technique used to solve complex problems.

Để hiểu đúng sự phân chia và chinh phục, trước tiên bạn nên hiểu khái niệm đệ quy. Recursion liên quan đến việc phá vỡ một vấn đề thành các vấn đề nhỏ hơn cho đến khi chúng đủ nhỏ để quản lý. Trong lập trình, đệ quy thường được thể hiện bằng một hàm tự gọi.recursion. Recursion involves breaking a problem down into smaller subproblems until they’re small enough to manage. In programming, recursion is usually expressed by a function calling itself.

Các thuật toán chia và chinh phục thường theo cùng một cấu trúc:

  1. Đầu vào ban đầu được chia thành nhiều phần, mỗi phần đại diện cho một biểu tượng con tương tự như bản gốc nhưng đơn giản hơn.
  2. Mỗi tiểu giải được giải quyết đệ quy.
  3. Các giải pháp cho tất cả các vấn đề phụ được kết hợp thành một giải pháp tổng thể duy nhất.

Trong trường hợp sắp xếp hợp nhất, cách tiếp cận phân chia và chinh phục chia tập hợp các giá trị đầu vào thành hai phần có kích thước bằng nhau, sắp xếp từng nửa một nửa và cuối cùng hợp nhất hai phần được sắp xếp này thành một danh sách được sắp xếp.

Thực hiện Sắp xếp hợp nhất trong Python

Việc thực hiện thuật toán sắp xếp hợp nhất cần hai phần khác nhau:

  1. Một chức năng chia nhỏ đầu vào một nửa
  2. Một chức năng hợp nhất cả hai nửa, tạo ra một mảng được sắp xếp

Tại đây, mã để hợp nhất hai mảng khác nhau:

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
1

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
05 nhận được hai mảng được sắp xếp khác nhau cần được hợp nhất với nhau. Quá trình để thực hiện điều này là đơn giản:

  • Dòng 4 và 9 Kiểm tra xem một trong hai mảng có trống không. Nếu một trong số họ là, thì không có gì để hợp nhất, vì vậy chức năng trả về mảng khác. check whether either of the arrays is empty. If one of them is, then there’s nothing to merge, so the function returns the other array.

  • Dòng 17 bắt đầu một vòng

     1def insertion_sort(array):
     2    # Loop from the second element of the array until
     3    # the last element
     4    for i in range(1, len(array)):
     5        # This is the element we want to position in its
     6        # correct place
     7        key_item = array[i]
     8
     9        # Initialize the variable that will be used to
    10        # find the correct position of the element referenced
    11        # by `key_item`
    12        j = i - 1
    13
    14        # Run through the list of items (the left
    15        # portion of the array) and find the correct position
    16        # of the element referenced by `key_item`. Do this only
    17        # if `key_item` is smaller than its adjacent values.
    18        while j >= 0 and array[j] > key_item:
    19            # Shift the value one position to the left
    20            # and reposition j to point to the next element
    21            # (from right to left)
    22            array[j + 1] = array[j]
    23            j -= 1
    24
    25        # When you finish shifting the elements, you can position
    26        # `key_item` in its correct location
    27        array[j + 1] = key_item
    28
    29    return array
    
    3 kết thúc bất cứ khi nào kết quả chứa tất cả các phần tử từ cả hai mảng được cung cấp. Mục tiêu là xem xét cả hai mảng và kết hợp các mục của họ để tạo ra một danh sách được sắp xếp. starts a
     1def insertion_sort(array):
     2    # Loop from the second element of the array until
     3    # the last element
     4    for i in range(1, len(array)):
     5        # This is the element we want to position in its
     6        # correct place
     7        key_item = array[i]
     8
     9        # Initialize the variable that will be used to
    10        # find the correct position of the element referenced
    11        # by `key_item`
    12        j = i - 1
    13
    14        # Run through the list of items (the left
    15        # portion of the array) and find the correct position
    16        # of the element referenced by `key_item`. Do this only
    17        # if `key_item` is smaller than its adjacent values.
    18        while j >= 0 and array[j] > key_item:
    19            # Shift the value one position to the left
    20            # and reposition j to point to the next element
    21            # (from right to left)
    22            array[j + 1] = array[j]
    23            j -= 1
    24
    25        # When you finish shifting the elements, you can position
    26        # `key_item` in its correct location
    27        array[j + 1] = key_item
    28
    29    return array
    
    3 loop that ends whenever the result contains all the elements from both of the supplied arrays. The goal is to look into both arrays and combine their items to produce a sorted list.

  • Dòng 21 so sánh các phần tử ở đầu của cả hai mảng, chọn giá trị nhỏ hơn và nối nó vào cuối mảng kết quả. compares the elements at the head of both arrays, selects the smaller value, and appends it to the end of the resultant array.

  • Các dòng 31 và 35 nối bất kỳ mục còn lại vào kết quả nếu tất cả các phần tử từ một trong hai mảng đã được sử dụng. append any remaining items to the result if all the elements from either of the arrays were already used.

Với chức năng ở trên, phần còn thiếu duy nhất là một hàm chia nhỏ mảng đầu vào và sử dụng

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
05 để tạo ra kết quả cuối cùng:

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
2

Ở đây, một bản tóm tắt nhanh chóng về mã:

  • Dòng 44 đóng vai trò là điều kiện dừng cho đệ quy. Nếu mảng đầu vào chứa ít hơn hai phần tử, thì hàm trả về mảng. Lưu ý rằng điều kiện này có thể được kích hoạt bằng cách nhận một mục hoặc một mảng trống. Trong cả hai trường hợp, không còn gì để sắp xếp, vì vậy chức năng sẽ trở lại. acts as the stopping condition for the recursion. If the input array contains fewer than two elements, then the function returns the array. Notice that this condition could be triggered by receiving either a single item or an empty array. In both cases, there’s nothing left to sort, so the function should return.

  • Dòng 47 tính toán điểm giữa của mảng. computes the middle point of the array.

  • Dòng 52 gọi

    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    05, vượt qua cả hai nửa được sắp xếp dưới dạng mảng. calls
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    05, passing both sorted halves as the arrays.

Lưu ý cách chức năng này tự gọi mình là đệ quy, giảm một nửa mảng mỗi lần. Mỗi lần lặp lại liên quan đến một mảng không bao giờ thu hút cho đến khi vẫn còn ít hơn hai yếu tố, có nghĩa là không còn gì để sắp xếp. Tại thời điểm này,

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
05 tiếp quản, hợp nhất hai nửa và tạo ra một danh sách được sắp xếp.recursively, halving the array each time. Each iteration deals with an ever-shrinking array until fewer than two elements remain, meaning there’s nothing left to sort. At this point,
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
05 takes over, merging the two halves and producing a sorted list.

Hãy xem một đại diện của các bước mà hợp nhất sắp xếp sẽ thực hiện để sắp xếp mảng

$ python sorting.py
Algorithm: sorted. Minimum execution time: 0.010945824000000007
8:

Hướng dẫn how fast is sort () in python? - sort () trong python nhanh như thế nào?
Quy trình sắp xếp hợp nhất

Con số sử dụng mũi tên màu vàng để biểu diễn một nửa mảng ở mỗi cấp độ đệ quy. Các mũi tên màu xanh lá cây đại diện cho việc hợp nhất mỗi Subarray trở lại với nhau. Các bước có thể được tóm tắt như sau:

  1. Cuộc gọi đầu tiên đến

    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    11 với
    $ python sorting.py
    Algorithm: sorted. Minimum execution time: 0.010945824000000007
    
    8 định nghĩa
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    13 là
     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    1.
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    13 được sử dụng để giảm một nửa mảng đầu vào thành
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    16 và
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    17, tạo ra
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    18 và
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    19, tương ứng.
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    11 sau đó được gọi đệ quy cho mỗi nửa để sắp xếp chúng một cách riêng biệt.

  2. Cuộc gọi đến

    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    11 với
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    18 tạo ra
     1def insertion_sort(array):
     2    # Loop from the second element of the array until
     3    # the last element
     4    for i in range(1, len(array)):
     5        # This is the element we want to position in its
     6        # correct place
     7        key_item = array[i]
     8
     9        # Initialize the variable that will be used to
    10        # find the correct position of the element referenced
    11        # by `key_item`
    12        j = i - 1
    13
    14        # Run through the list of items (the left
    15        # portion of the array) and find the correct position
    16        # of the element referenced by `key_item`. Do this only
    17        # if `key_item` is smaller than its adjacent values.
    18        while j >= 0 and array[j] > key_item:
    19            # Shift the value one position to the left
    20            # and reposition j to point to the next element
    21            # (from right to left)
    22            array[j + 1] = array[j]
    23            j -= 1
    24
    25        # When you finish shifting the elements, you can position
    26        # `key_item` in its correct location
    27        array[j + 1] = key_item
    28
    29    return array
    
    8 và
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    24. Quá trình lặp lại cho mỗi nửa này.

  3. Cuộc gọi đến

    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    11 với
     1def insertion_sort(array):
     2    # Loop from the second element of the array until
     3    # the last element
     4    for i in range(1, len(array)):
     5        # This is the element we want to position in its
     6        # correct place
     7        key_item = array[i]
     8
     9        # Initialize the variable that will be used to
    10        # find the correct position of the element referenced
    11        # by `key_item`
    12        j = i - 1
    13
    14        # Run through the list of items (the left
    15        # portion of the array) and find the correct position
    16        # of the element referenced by `key_item`. Do this only
    17        # if `key_item` is smaller than its adjacent values.
    18        while j >= 0 and array[j] > key_item:
    19            # Shift the value one position to the left
    20            # and reposition j to point to the next element
    21            # (from right to left)
    22            array[j + 1] = array[j]
    23            j -= 1
    24
    25        # When you finish shifting the elements, you can position
    26        # `key_item` in its correct location
    27        array[j + 1] = key_item
    28
    29    return array
    
    8 trả về
     1def insertion_sort(array):
     2    # Loop from the second element of the array until
     3    # the last element
     4    for i in range(1, len(array)):
     5        # This is the element we want to position in its
     6        # correct place
     7        key_item = array[i]
     8
     9        # Initialize the variable that will be used to
    10        # find the correct position of the element referenced
    11        # by `key_item`
    12        j = i - 1
    13
    14        # Run through the list of items (the left
    15        # portion of the array) and find the correct position
    16        # of the element referenced by `key_item`. Do this only
    17        # if `key_item` is smaller than its adjacent values.
    18        while j >= 0 and array[j] > key_item:
    19            # Shift the value one position to the left
    20            # and reposition j to point to the next element
    21            # (from right to left)
    22            array[j + 1] = array[j]
    23            j -= 1
    24
    25        # When you finish shifting the elements, you can position
    26        # `key_item` in its correct location
    27        array[j + 1] = key_item
    28
    29    return array
    
    8 vì đó là yếu tố duy nhất. Điều tương tự cũng xảy ra với cuộc gọi đến
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    11 với
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    24.

  4. Tại thời điểm này, chức năng bắt đầu hợp nhất các subarrays lại với nhau bằng cách sử dụng ____105, bắt đầu bằng

     1def insertion_sort(array):
     2    # Loop from the second element of the array until
     3    # the last element
     4    for i in range(1, len(array)):
     5        # This is the element we want to position in its
     6        # correct place
     7        key_item = array[i]
     8
     9        # Initialize the variable that will be used to
    10        # find the correct position of the element referenced
    11        # by `key_item`
    12        j = i - 1
    13
    14        # Run through the list of items (the left
    15        # portion of the array) and find the correct position
    16        # of the element referenced by `key_item`. Do this only
    17        # if `key_item` is smaller than its adjacent values.
    18        while j >= 0 and array[j] > key_item:
    19            # Shift the value one position to the left
    20            # and reposition j to point to the next element
    21            # (from right to left)
    22            array[j + 1] = array[j]
    23            j -= 1
    24
    25        # When you finish shifting the elements, you can position
    26        # `key_item` in its correct location
    27        array[j + 1] = key_item
    28
    29    return array
    
    8 và
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    24 làm mảng đầu vào, tạo ra
     1if __name__ == "__main__":
     2    # Generate an array of `ARRAY_LENGTH` items consisting
     3    # of random integer values between 0 and 999
     4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
     5
     6    # Call the function using the name of the sorting algorithm
     7    # and the array we just created
     8    run_sorting_algorithm(algorithm="insertion_sort", array=array)
    
    5 do kết quả.

  5. Ở phía bên kia,

    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    19 bị phá vỡ đệ quy và được hợp nhất bằng cách sử dụng cùng một quy trình, tạo ra
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    35 do kết quả.

  6. Trong bước cuối cùng,

     1if __name__ == "__main__":
     2    # Generate an array of `ARRAY_LENGTH` items consisting
     3    # of random integer values between 0 and 999
     4    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
     5
     6    # Call the function using the name of the sorting algorithm
     7    # and the array we just created
     8    run_sorting_algorithm(algorithm="insertion_sort", array=array)
    
    5 và
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    35 được hợp nhất lại với
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    05, tạo ra kết quả cuối cùng:
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    39.

Đo lường sự phức tạp của Merge sắp xếp o

Để phân tích sự phức tạp của Sắp xếp hợp nhất, bạn có thể nhìn vào hai bước của nó một cách riêng biệt:

  1. >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    05 có thời gian chạy tuyến tính. Nó nhận được hai mảng có chiều dài kết hợp nhiều nhất là N (độ dài của mảng đầu vào ban đầu) và nó kết hợp cả hai mảng bằng cách nhìn vào từng phần tử nhiều nhất một lần. Điều này dẫn đến độ phức tạp thời gian chạy của O (N).

  2. Bước thứ hai phân tách mảng đầu vào đệ quy và gọi

    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    05 cho mỗi nửa. Vì mảng được giảm một nửa cho đến khi một phần tử duy nhất vẫn còn, tổng số hoạt động giảm một nửa được thực hiện bởi hàm này là log2n. Vì
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    05 được gọi cho mỗi nửa, chúng tôi nhận được tổng thời gian chạy O (n log2N).O(n log2n).

Thật thú vị, O (n log2n) là thời gian chạy trong trường hợp xấu nhất có thể có thể đạt được bằng thuật toán sắp xếp.

Thời gian thực hiện sắp xếp hợp nhất của bạn

Để so sánh tốc độ hợp nhất sắp xếp với hai triển khai trước đó, bạn có thể sử dụng cùng một cơ chế như trước đây và thay thế tên của thuật toán trong dòng 8:line 8:

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
3

Bạn có thể thực thi tập lệnh để có thời gian thực hiện là

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
43:

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
4

So với sắp xếp bong bóng và sắp xếp chèn, việc triển khai Merge sắp xếp cực kỳ nhanh, sắp xếp mảng mười nghìn phần tử trong chưa đầy một giây!

Phân tích điểm mạnh và điểm yếu của sự hợp nhất

Nhờ độ phức tạp thời gian chạy của O (n log2N), Merge Sort là một thuật toán rất hiệu quả, có tỷ lệ tốt như kích thước của mảng đầu vào phát triển. Nó cũng đơn giản để song song hóa vì nó chia mảng đầu vào thành các khối có thể được phân phối và xử lý song song nếu cần thiết.parallelize because it breaks the input array into chunks that can be distributed and processed in parallel if necessary.

Điều đó nói rằng, đối với các danh sách nhỏ, chi phí thời gian của đệ quy cho phép các thuật toán như sắp xếp bong bóng và sắp xếp chèn nhanh hơn. Ví dụ: chạy thử nghiệm với danh sách mười yếu tố dẫn đến các thời điểm sau:

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
5

Cả hai loại bong bóng và chèn sắp xếp Beat Merge sắp xếp khi sắp xếp một danh sách mười phần tử.

Một nhược điểm khác của Sắp xếp hợp nhất là nó tạo ra các bản sao của mảng khi tự gọi mình là đệ quy. Nó cũng tạo ra một danh sách mới bên trong

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
05 để sắp xếp và trả lại cả hai nửa đầu vào. Điều này làm cho Sắp xếp hợp nhất sử dụng nhiều bộ nhớ hơn so với sắp xếp bong bóng và sắp xếp chèn, cả hai đều có thể sắp xếp danh sách tại chỗ.

Do giới hạn này, bạn có thể không muốn sử dụng Merge sắp xếp để sắp xếp các danh sách lớn trong phần cứng bị hạn chế bộ nhớ.

Thuật toán Quicksort trong Python

Giống như Merge sắp xếp, thuật toán QuickSort áp dụng nguyên tắc phân chia và chinh phục để chia mảng đầu vào thành hai danh sách, thứ nhất với các mục nhỏ và thứ hai với các mục lớn. Thuật toán sau đó sắp xếp cả hai danh sách đệ quy cho đến khi danh sách kết quả được sắp xếp hoàn toàn.Quicksort algorithm applies the divide-and-conquer principle to divide the input array into two lists, the first with small items and the second with large items. The algorithm then sorts both lists recursively until the resultant list is completely sorted.

Chia danh sách đầu vào được gọi là phân vùng danh sách. QuickSort trước tiên chọn một phần tử

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45 và phân vùng danh sách xung quanh
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45, đặt mọi phần tử nhỏ hơn vào một mảng
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
47 và mọi phần tử lớn hơn vào một mảng
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
48.partitioning the list. Quicksort first selects a
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45 element and partitions the list around the
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45, putting every smaller element into a
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
47 array and every larger element into a
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
48 array.

Đặt mọi yếu tố từ danh sách

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
47 vào bên trái của
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45 và mọi yếu tố từ danh sách
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
48 đến đúng vị trí
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45 chính xác để có trong danh sách được sắp xếp cuối cùng. Điều này có nghĩa là chức năng hiện có thể áp dụng quy trình tương tự một cách đệ quy cho
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
47 và sau đó
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
48 cho đến khi toàn bộ danh sách được sắp xếp.

Thực hiện Quicksort trong Python

Tại đây, một triển khai khá nhỏ gọn của Quicksort:

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
6

Ở đây, một bản tóm tắt của mã:

  • Dòng 6 dừng hàm đệ quy nếu mảng chứa ít hơn hai phần tử. stops the recursive function if the array contains fewer than two elements.

  • Dòng 12 chọn phần tử

    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    45 ngẫu nhiên từ danh sách và tiến hành phân vùng danh sách. selects the
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    45 element randomly from the list and proceeds to partition the list.

  • Các dòng 19 và 20 đưa mọi yếu tố mà nhỏ hơn

    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    45 vào danh sách gọi là
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    47.
    put every element that’s smaller than
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    45 into the list called
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    47.

  • Các dòng 21 và 22 đưa mọi yếu tố mà từ đó bằng

    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    45 vào danh sách gọi là
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    59.
    put every element that’s equal to
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    45 into the list called
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    59.

  • Các dòng 23 và 24 đưa mọi yếu tố mà LỚN lớn hơn

    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    45 vào danh sách gọi là
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    48.
    put every element that’s larger than
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    45 into the list called
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    48.

  • Dòng 28 sắp xếp các danh sách

    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    47 và
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    48 và kết hợp chúng cùng với nội dung của danh sách
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    59.
    recursively sorts the
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    47 and
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    48 lists and combines them along with the contents of the
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    59 list.

Ở đây, một minh họa về các bước mà QuickSort thực hiện để sắp xếp mảng

$ python sorting.py
Algorithm: sorted. Minimum execution time: 0.010945824000000007
8:

Hướng dẫn how fast is sort () in python? - sort () trong python nhanh như thế nào?
Quá trình Quicksort

Các đường màu vàng biểu thị phân vùng của mảng thành ba danh sách:

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
47,
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
59 và
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
48. Các đường màu xanh lá cây đại diện cho việc sắp xếp và đặt các danh sách này lại với nhau. Ở đây, một lời giải thích ngắn gọn về các bước:

  1. Phần tử

    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    45 được chọn ngẫu nhiên. Trong trường hợp này,
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    45 là
     1def bubble_sort(array):
     2    n = len(array)
     3
     4    for i in range(n):
     5        # Create a flag that will allow the function to
     6        # terminate early if there's nothing left to sort
     7        already_sorted = True
     8
     9        # Start looking at each item of the list one by one,
    10        # comparing it with its adjacent value. With each
    11        # iteration, the portion of the array that you look at
    12        # shrinks because the remaining items have already been
    13        # sorted.
    14        for j in range(n - i - 1):
    15            if array[j] > array[j + 1]:
    16                # If the item you're looking at is greater than its
    17                # adjacent value, then swap them
    18                array[j], array[j + 1] = array[j + 1], array[j]
    19
    20                # Since you had to swap two elements,
    21                # set the `already_sorted` flag to `False` so the
    22                # algorithm doesn't finish prematurely
    23                already_sorted = False
    24
    25        # If there were no swaps during the last iteration,
    26        # the array is already sorted, and you can terminate
    27        if already_sorted:
    28            break
    29
    30    return array
    
    5.

  2. Các phân vùng vượt qua đầu tiên của mảng đầu vào sao cho

    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    47 chứa
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    73,
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    59 chứa
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    75 và
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    48 chứa
     1def insertion_sort(array):
     2    # Loop from the second element of the array until
     3    # the last element
     4    for i in range(1, len(array)):
     5        # This is the element we want to position in its
     6        # correct place
     7        key_item = array[i]
     8
     9        # Initialize the variable that will be used to
    10        # find the correct position of the element referenced
    11        # by `key_item`
    12        j = i - 1
    13
    14        # Run through the list of items (the left
    15        # portion of the array) and find the correct position
    16        # of the element referenced by `key_item`. Do this only
    17        # if `key_item` is smaller than its adjacent values.
    18        while j >= 0 and array[j] > key_item:
    19            # Shift the value one position to the left
    20            # and reposition j to point to the next element
    21            # (from right to left)
    22            array[j + 1] = array[j]
    23            j -= 1
    24
    25        # When you finish shifting the elements, you can position
    26        # `key_item` in its correct location
    27        array[j + 1] = key_item
    28
    29    return array
    
    8.

  3. >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    78 sau đó được gọi là đệ quy với
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    47 làm đầu vào của nó. Điều này chọn một
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    45 ngẫu nhiên và chia mảng thành
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    24 là
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    47,
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    83 là
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    59 và
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    85 là
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    48.

  4. Quá trình này vẫn tiếp tục, nhưng tại thời điểm này, cả

    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    47 và
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    48 đều có ít hơn hai mặt hàng mỗi mục. Điều này kết thúc đệ quy, và chức năng đặt mảng lại với nhau. Thêm
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    47 và
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    48 được sắp xếp vào một trong hai bên của danh sách
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    59 tạo ra
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    73.

  5. Mặt khác, danh sách

    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    48 chứa
     1def insertion_sort(array):
     2    # Loop from the second element of the array until
     3    # the last element
     4    for i in range(1, len(array)):
     5        # This is the element we want to position in its
     6        # correct place
     7        key_item = array[i]
     8
     9        # Initialize the variable that will be used to
    10        # find the correct position of the element referenced
    11        # by `key_item`
    12        j = i - 1
    13
    14        # Run through the list of items (the left
    15        # portion of the array) and find the correct position
    16        # of the element referenced by `key_item`. Do this only
    17        # if `key_item` is smaller than its adjacent values.
    18        while j >= 0 and array[j] > key_item:
    19            # Shift the value one position to the left
    20            # and reposition j to point to the next element
    21            # (from right to left)
    22            array[j + 1] = array[j]
    23            j -= 1
    24
    25        # When you finish shifting the elements, you can position
    26        # `key_item` in its correct location
    27        array[j + 1] = key_item
    28
    29    return array
    
    8 có ít hơn hai phần tử, do đó, thuật toán trả về mảng
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    47 được sắp xếp, hiện là
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    73. Hợp nhất nó với
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    59 (
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    75) và
    >>> array = [8, 2, 6, 4, 5]
    >>> sorted(array)
    [2, 4, 5, 6, 8]
    
    48 (
     1def insertion_sort(array):
     2    # Loop from the second element of the array until
     3    # the last element
     4    for i in range(1, len(array)):
     5        # This is the element we want to position in its
     6        # correct place
     7        key_item = array[i]
     8
     9        # Initialize the variable that will be used to
    10        # find the correct position of the element referenced
    11        # by `key_item`
    12        j = i - 1
    13
    14        # Run through the list of items (the left
    15        # portion of the array) and find the correct position
    16        # of the element referenced by `key_item`. Do this only
    17        # if `key_item` is smaller than its adjacent values.
    18        while j >= 0 and array[j] > key_item:
    19            # Shift the value one position to the left
    20            # and reposition j to point to the next element
    21            # (from right to left)
    22            array[j + 1] = array[j]
    23            j -= 1
    24
    25        # When you finish shifting the elements, you can position
    26        # `key_item` in its correct location
    27        array[j + 1] = key_item
    28
    29    return array
    
    8) tạo ra danh sách được sắp xếp cuối cùng.

Chọn phần tử >>> array = [8, 2, 6, 4, 5] >>> sorted(array) [2, 4, 5, 6, 8] 45

Tại sao việc triển khai ở trên chọn phần tử

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45 một cách ngẫu nhiên? Sẽ là giống nhau để nhất quán chọn phần tử đầu tiên hoặc cuối cùng của danh sách đầu vào?

Do cách thức hoạt động của thuật toán Quicksort, số lượng cấp độ đệ quy phụ thuộc vào nơi

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45 kết thúc trong mỗi phân vùng. Trong trường hợp tốt nhất, thuật toán luôn chọn phần tử trung bình là
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45. Điều đó sẽ làm cho mỗi biểu tượng được tạo ra chính xác bằng một nửa của vấn đề trước đó, dẫn đến nhiều cấp độ log2N.median element as the
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45. That would make each generated subproblem exactly half the size of the previous problem, leading to at most log2n levels.

Mặt khác, nếu thuật toán luôn chọn phần tử nhỏ nhất hoặc lớn nhất của mảng là

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45, thì các phân vùng được tạo sẽ không bằng nhau nhất có thể, dẫn đến mức độ đệ quy N-1. Đó sẽ là kịch bản trường hợp xấu nhất cho Quicksort.

Như bạn có thể thấy, hiệu quả của QuickSort, thường phụ thuộc vào lựa chọn

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45. Nếu mảng đầu vào chưa được phân loại, thì sử dụng phần tử đầu tiên hoặc cuối cùng vì
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45 sẽ hoạt động giống như một phần tử ngẫu nhiên. Nhưng nếu mảng đầu vào được sắp xếp hoặc gần như được sắp xếp, sử dụng phần tử đầu tiên hoặc cuối cùng vì
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45 có thể dẫn đến một trường hợp xấu nhất. Chọn
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45 một cách ngẫu nhiên khiến cho nhiều khả năng QuickSort sẽ chọn một giá trị gần với trung bình và kết thúc nhanh hơn.

Một tùy chọn khác để chọn

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45 là tìm giá trị trung bình của mảng và buộc thuật toán sử dụng nó làm
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45. Điều này có thể được thực hiện trong thời gian O (N). Mặc dù quá trình này có liên quan nhiều hơn một chút, nhưng sử dụng giá trị trung bình làm
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45 cho Quicksort đảm bảo bạn sẽ có kịch bản O tốt nhất.

Đo lường sự phức tạp của Quicksort từ O

Với QuickSort, danh sách đầu vào được phân vùng theo thời gian tuyến tính, O (n) và quá trình này lặp lại đệ quy một trung bình của log2n lần. Điều này dẫn đến sự phức tạp cuối cùng của O (n log2n).O(n log2n).

Điều đó nói rằng, hãy nhớ các cuộc thảo luận về cách lựa chọn

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45 ảnh hưởng đến thời gian chạy của thuật toán. Kịch bản trường hợp tốt nhất O (N) xảy ra khi
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45 được chọn gần với trung bình của mảng và kịch bản O (N2) xảy ra khi
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45 là giá trị nhỏ nhất hoặc lớn nhất của mảng.

Về mặt lý thuyết, nếu thuật toán tập trung đầu tiên vào việc tìm giá trị trung bình và sau đó sử dụng nó làm phần tử

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45, thì độ phức tạp trong trường hợp xấu nhất sẽ đi xuống O (n log2N). Trung bình của một mảng có thể được tìm thấy trong thời gian tuyến tính và sử dụng nó làm
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45 đảm bảo phần QuickSort của mã sẽ thực hiện trong O (n log2N).

Bằng cách sử dụng giá trị trung bình là

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
45, bạn sẽ kết thúc với thời gian chạy cuối cùng của O (n) + O (n log2N). Bạn có thể đơn giản hóa điều này xuống O (n log2N) vì phần logarit phát triển nhanh hơn nhiều so với phần tuyến tính.

Thời gian triển khai Quicksort của bạn

Đến bây giờ, bạn đã quen thuộc với quá trình thời gian chạy của thuật toán. Chỉ cần thay đổi tên của thuật toán trong dòng 8:line 8:

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
7

Bạn có thể thực thi tập lệnh như bạn có trước đây:

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
8

Quicksort hoàn thiện không chỉ trong vòng chưa đầy một giây, mà còn nhanh hơn nhiều so với sự hợp nhất (

 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
19 giây so với
 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
20 giây). Việc tăng số lượng các phần tử được chỉ định bởi
 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
21 từ
 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
22 lên
 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
23 và chạy tập lệnh lại kết thúc với việc kết thúc sắp xếp hợp nhất trong
 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
24 giây, trong khi QuickSort sắp xếp danh sách chỉ trong một
 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
25 giây.

Phân tích điểm mạnh và điểm yếu của Quicksort

Đúng như tên của nó, Quicksort rất nhanh. Mặc dù trường hợp xấu nhất của nó là về mặt lý thuyết O (N2), nhưng trong thực tế, việc triển khai tốt các nhịp đập nhanh hầu hết các triển khai sắp xếp khác. Ngoài ra, giống như Merge sắp xếp, Quicksort rất đơn giản để song song hóa.parallelize.

Một trong những nhược điểm chính của Quicksort, là thiếu đảm bảo rằng nó sẽ đạt được độ phức tạp thời gian chạy trung bình. Mặc dù các trường hợp xấu nhất là rất hiếm, một số ứng dụng nhất định có thể đủ khả năng để có nguy cơ hiệu suất kém, vì vậy chúng chọn các thuật toán ở trong O (n log2N) bất kể đầu vào.

Cũng giống như Merge sắp xếp, Quicksort cũng giao dịch không gian bộ nhớ cho tốc độ. Điều này có thể trở thành một hạn chế để sắp xếp các danh sách lớn hơn.

Một thử nghiệm nhanh sắp xếp danh sách mười yếu tố dẫn đến kết quả sau:

>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
9

Kết quả cho thấy Quicksort cũng trả giá đệ quy khi danh sách đủ nhỏ, mất nhiều thời gian hơn để hoàn thành so với cả hai loại chèn và sắp xếp bong bóng.

Thuật toán Timsort trong Python

Thuật toán TIMSORT được coi là một thuật toán sắp xếp lai vì nó sử dụng sự kết hợp tốt nhất của cả hai thế giới của loại chèn và sắp xếp hợp nhất. Timsort gần và thân yêu với cộng đồng Python vì nó được tạo ra bởi Tim Peters vào năm 2002 để được sử dụng làm thuật toán sắp xếp tiêu chuẩn của ngôn ngữ Python.Timsort algorithm is considered a hybrid sorting algorithm because it employs a best-of-both-worlds combination of insertion sort and merge sort. Timsort is near and dear to the Python community because it was created by Tim Peters in 2002 to be used as the standard sorting algorithm of the Python language.

Đặc điểm chính của Timsort là nó tận dụng các yếu tố đã được phân loại tồn tại trong hầu hết các bộ dữ liệu trong thế giới thực. Chúng được gọi là chạy tự nhiên. Thuật toán sau đó lặp lại trong danh sách, thu thập các yếu tố thành chạy và hợp nhất chúng vào một danh sách được sắp xếp duy nhất.natural runs. The algorithm then iterates over the list, collecting the elements into runs and merging them into a single sorted list.

Thực hiện Timsort trong Python

Trong phần này, bạn sẽ tạo ra một triển khai Python Barebones minh họa tất cả các phần của thuật toán Timsort. Nếu bạn quan tâm, bạn cũng có thể kiểm tra triển khai C gốc của Timsort.

Bước đầu tiên trong việc thực hiện TimSort là sửa đổi việc triển khai

$ python sorting.py
Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
7 từ trước:

 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
0

Việc thực hiện sửa đổi này bổ sung một vài tham số,

 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
27 và
 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
28, chỉ ra phần nào của mảng sẽ được sắp xếp. Điều này cho phép thuật toán TIMSORT sắp xếp một phần của mảng tại chỗ. Sửa đổi chức năng thay vì tạo một cái mới có nghĩa là nó có thể được sử dụng lại cho cả sắp xếp chèn và Timsort.

Bây giờ hãy xem việc thực hiện Timsort:

 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
1

Mặc dù việc triển khai phức tạp hơn một chút so với các thuật toán trước đó, chúng ta có thể tóm tắt nó một cách nhanh chóng theo cách sau:

  • Dòng 8 và 9 tạo ra các lát nhỏ, hoặc chạy của mảng và sắp xếp chúng bằng cách sử dụng sắp xếp chèn. Bạn đã học được trước đây rằng loại chèn rất nhanh trong các danh sách nhỏ và Timsort tận dụng lợi thế này. TIMSORT sử dụng các tham số

     1from random import randint
     2from timeit import repeat
     3
     4def run_sorting_algorithm(algorithm, array):
     5    # Set up the context and prepare the call to the specified
     6    # algorithm using the supplied array. Only import the
     7    # algorithm function if it's not the built-in `sorted()`.
     8    setup_code = f"from __main__ import {algorithm}" \
     9        if algorithm != "sorted" else ""
    10
    11    stmt = f"{algorithm}({array})"
    12
    13    # Execute the code ten different times and return the time
    14    # in seconds that each execution took
    15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
    16
    17    # Finally, display the name of the algorithm and the
    18    # minimum time it took to run
    19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
    
    27 và
     1from random import randint
     2from timeit import repeat
     3
     4def run_sorting_algorithm(algorithm, array):
     5    # Set up the context and prepare the call to the specified
     6    # algorithm using the supplied array. Only import the
     7    # algorithm function if it's not the built-in `sorted()`.
     8    setup_code = f"from __main__ import {algorithm}" \
     9        if algorithm != "sorted" else ""
    10
    11    stmt = f"{algorithm}({array})"
    12
    13    # Execute the code ten different times and return the time
    14    # in seconds that each execution took
    15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
    16
    17    # Finally, display the name of the algorithm and the
    18    # minimum time it took to run
    19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
    
    28 mới được giới thiệu trong
    $ python sorting.py
    Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
    
    7 để sắp xếp danh sách tại chỗ mà không phải tạo các mảng mới như Merge Sort và QuickSort Do.
    create small slices, or runs, of the array and sort them using insertion sort. You learned previously that insertion sort is speedy on small lists, and Timsort takes advantage of this. Timsort uses the newly introduced
     1from random import randint
     2from timeit import repeat
     3
     4def run_sorting_algorithm(algorithm, array):
     5    # Set up the context and prepare the call to the specified
     6    # algorithm using the supplied array. Only import the
     7    # algorithm function if it's not the built-in `sorted()`.
     8    setup_code = f"from __main__ import {algorithm}" \
     9        if algorithm != "sorted" else ""
    10
    11    stmt = f"{algorithm}({array})"
    12
    13    # Execute the code ten different times and return the time
    14    # in seconds that each execution took
    15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
    16
    17    # Finally, display the name of the algorithm and the
    18    # minimum time it took to run
    19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
    
    27 and
     1from random import randint
     2from timeit import repeat
     3
     4def run_sorting_algorithm(algorithm, array):
     5    # Set up the context and prepare the call to the specified
     6    # algorithm using the supplied array. Only import the
     7    # algorithm function if it's not the built-in `sorted()`.
     8    setup_code = f"from __main__ import {algorithm}" \
     9        if algorithm != "sorted" else ""
    10
    11    stmt = f"{algorithm}({array})"
    12
    13    # Execute the code ten different times and return the time
    14    # in seconds that each execution took
    15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
    16
    17    # Finally, display the name of the algorithm and the
    18    # minimum time it took to run
    19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
    
    28 parameters in
    $ python sorting.py
    Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
    
    7 to sort the list in place without having to create new arrays like merge sort and Quicksort do.

  • Dòng 16 hợp nhất các lần chạy nhỏ hơn này, với mỗi lần chạy có kích thước

     1from random import randint
     2from timeit import repeat
     3
     4def run_sorting_algorithm(algorithm, array):
     5    # Set up the context and prepare the call to the specified
     6    # algorithm using the supplied array. Only import the
     7    # algorithm function if it's not the built-in `sorted()`.
     8    setup_code = f"from __main__ import {algorithm}" \
     9        if algorithm != "sorted" else ""
    10
    11    stmt = f"{algorithm}({array})"
    12
    13    # Execute the code ten different times and return the time
    14    # in seconds that each execution took
    15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
    16
    17    # Finally, display the name of the algorithm and the
    18    # minimum time it took to run
    19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
    
    32 ban đầu. Với mỗi lần lặp, kích thước của các lần chạy được nhân đôi và thuật toán tiếp tục hợp nhất các lần chạy lớn hơn này cho đến khi một lần chạy được sắp xếp duy nhất. merges these smaller runs, with each run being of size
     1from random import randint
     2from timeit import repeat
     3
     4def run_sorting_algorithm(algorithm, array):
     5    # Set up the context and prepare the call to the specified
     6    # algorithm using the supplied array. Only import the
     7    # algorithm function if it's not the built-in `sorted()`.
     8    setup_code = f"from __main__ import {algorithm}" \
     9        if algorithm != "sorted" else ""
    10
    11    stmt = f"{algorithm}({array})"
    12
    13    # Execute the code ten different times and return the time
    14    # in seconds that each execution took
    15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
    16
    17    # Finally, display the name of the algorithm and the
    18    # minimum time it took to run
    19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
    
    32 initially. With each iteration, the size of the runs is doubled, and the algorithm continues merging these larger runs until a single sorted run remains.

Lưu ý làm thế nào, không giống như Merge sắp xếp, Timsort hợp nhất Subarrays đã được sắp xếp trước đó. Làm như vậy làm giảm tổng số so sánh cần thiết để tạo ra một danh sách được sắp xếp. Lợi thế này so với Sắp xếp hợp nhất sẽ trở nên rõ ràng khi chạy thử nghiệm bằng các mảng khác nhau.

Cuối cùng, dòng 2 xác định

 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
33. Có hai lý do để sử dụng
 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
32 làm giá trị ở đây:line 2 defines
 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
33. There are two reasons for using
 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
32 as the value here:

  1. Việc sắp xếp các mảng nhỏ bằng cách sử dụng sắp xếp chèn là rất nhanh và

     1from random import randint
     2from timeit import repeat
     3
     4def run_sorting_algorithm(algorithm, array):
     5    # Set up the context and prepare the call to the specified
     6    # algorithm using the supplied array. Only import the
     7    # algorithm function if it's not the built-in `sorted()`.
     8    setup_code = f"from __main__ import {algorithm}" \
     9        if algorithm != "sorted" else ""
    10
    11    stmt = f"{algorithm}({array})"
    12
    13    # Execute the code ten different times and return the time
    14    # in seconds that each execution took
    15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
    16
    17    # Finally, display the name of the algorithm and the
    18    # minimum time it took to run
    19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
    
    35 có một giá trị nhỏ để tận dụng đặc tính này. Khởi tạo
     1from random import randint
     2from timeit import repeat
     3
     4def run_sorting_algorithm(algorithm, array):
     5    # Set up the context and prepare the call to the specified
     6    # algorithm using the supplied array. Only import the
     7    # algorithm function if it's not the built-in `sorted()`.
     8    setup_code = f"from __main__ import {algorithm}" \
     9        if algorithm != "sorted" else ""
    10
    11    stmt = f"{algorithm}({array})"
    12
    13    # Execute the code ten different times and return the time
    14    # in seconds that each execution took
    15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
    16
    17    # Finally, display the name of the algorithm and the
    18    # minimum time it took to run
    19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
    
    35 với một giá trị mà quá lớn sẽ đánh bại mục đích sử dụng sắp xếp chèn và sẽ làm cho thuật toán chậm hơn.

  2. Hợp nhất hai danh sách cân bằng hiệu quả hơn nhiều so với danh sách hợp nhất có kích thước không cân xứng. Chọn một giá trị

     1from random import randint
     2from timeit import repeat
     3
     4def run_sorting_algorithm(algorithm, array):
     5    # Set up the context and prepare the call to the specified
     6    # algorithm using the supplied array. Only import the
     7    # algorithm function if it's not the built-in `sorted()`.
     8    setup_code = f"from __main__ import {algorithm}" \
     9        if algorithm != "sorted" else ""
    10
    11    stmt = f"{algorithm}({array})"
    12
    13    # Execute the code ten different times and return the time
    14    # in seconds that each execution took
    15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
    16
    17    # Finally, display the name of the algorithm and the
    18    # minimum time it took to run
    19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
    
    35 mà một sức mạnh của hai người đảm bảo hiệu suất tốt hơn khi hợp nhất tất cả các lần chạy khác nhau mà thuật toán tạo ra.

Kết hợp cả hai điều kiện ở trên cung cấp một số tùy chọn cho

 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
35. Việc thực hiện trong hướng dẫn này sử dụng
 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
33 làm một trong những khả năng.

Đo lường độ phức tạp của Timsort từ O

Trung bình, độ phức tạp của TimSort là O (N log2n), giống như Sắp xếp hợp nhất và Quicksort. Phần logarit xuất phát từ việc nhân đôi kích thước của lần chạy để thực hiện từng thao tác hợp nhất tuyến tính.O(n log2n), just like merge sort and Quicksort. The logarithmic part comes from doubling the size of the run to perform each linear merge operation.

Tuy nhiên, Timsort thực hiện đặc biệt tốt trên các danh sách đã được phân loại hoặc gần được sắp xếp, dẫn đến một trường hợp tốt nhất của O (N). Trong trường hợp này, Timsort rõ ràng đánh bại Merge Sắp xếp và phù hợp với kịch bản trường hợp tốt nhất cho Quicksort. Nhưng trường hợp xấu nhất đối với Timsort cũng là O (N log2N), vượt qua Quicksort, O (N2).

Thời gian triển khai Timsort của bạn

Bạn có thể sử dụng

21ARRAY_LENGTH = 10000
22
23if __name__ == "__main__":
24    # Generate an array of `ARRAY_LENGTH` items consisting
25    # of random integer values between 0 and 999
26    array = [randint(0, 1000) for i in range(ARRAY_LENGTH)]
27
28    # Call the function using the name of the sorting algorithm
29    # and the array you just created
30    run_sorting_algorithm(algorithm="sorted", array=array)
9 để xem Timsort thực hiện cách sắp xếp mảng mười nghìn phần tử:

 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
2

Bây giờ thực thi tập lệnh để có thời gian thực hiện là

 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
41:

 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
3

 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
42 giây, việc triển khai TIMSORT này là
 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
43 giây, hoặc 17 %, nhanh hơn so với phân loại hợp nhất, mặc dù nó không khớp với
 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
19 của Quicksort. Nó cũng là một loại nhanh hơn 11.000 phần trăm lố bịch so với sắp xếp chèn!

Bây giờ hãy cố gắng sắp xếp một danh sách đã được phân loại bằng bốn thuật toán này và xem điều gì sẽ xảy ra. Bạn có thể sửa đổi phần

 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
45 của mình như sau:

 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
4

Nếu bạn thực thi tập lệnh ngay bây giờ, thì tất cả các thuật toán sẽ chạy và xuất ra thời gian thực hiện tương ứng của chúng:

 1from random import randint
 2from timeit import repeat
 3
 4def run_sorting_algorithm(algorithm, array):
 5    # Set up the context and prepare the call to the specified
 6    # algorithm using the supplied array. Only import the
 7    # algorithm function if it's not the built-in `sorted()`.
 8    setup_code = f"from __main__ import {algorithm}" \
 9        if algorithm != "sorted" else ""
10
11    stmt = f"{algorithm}({array})"
12
13    # Execute the code ten different times and return the time
14    # in seconds that each execution took
15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
16
17    # Finally, display the name of the algorithm and the
18    # minimum time it took to run
19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
5

Lần này, Timsort xuất hiện nhanh hơn ba mươi bảy phần trăm so với phân loại hợp nhất và năm phần trăm nhanh hơn so với Quicksort, uốn cong khả năng tận dụng các lần chạy đã được phân loại.

Lưu ý cách Timsort hưởng lợi từ hai thuật toán chậm hơn nhiều khi được sử dụng bởi chính chúng. Thiên tài của Timsort là kết hợp các thuật toán này và chơi theo thế mạnh của họ để đạt được kết quả ấn tượng.

Phân tích điểm mạnh và điểm yếu của Timsort

Nhược điểm chính của Timsort là sự phức tạp của nó. Mặc dù thực hiện một phiên bản rất đơn giản của thuật toán gốc, nhưng nó vẫn đòi hỏi nhiều mã hơn vì nó dựa vào cả

$ python sorting.py
Algorithm: bubble_sort. Minimum execution time: 73.21720498399998
7 và
>>> array = [8, 2, 6, 4, 5]
>>> sorted(array)
[2, 4, 5, 6, 8]
05.

Một trong những ưu điểm của Timsort, là khả năng dự đoán thực hiện trong O (n log2N) của nó bất kể cấu trúc của mảng đầu vào. Tương phản rằng với Quicksort, có thể làm suy giảm xuống O (N2). Timsort cũng rất nhanh đối với các mảng nhỏ vì thuật toán biến thành một loại chèn duy nhất.

Đối với việc sử dụng trong thế giới thực, trong đó nó phổ biến để sắp xếp các mảng đã có một số thứ tự có từ trước, Timsort là một lựa chọn tuyệt vời. Khả năng thích ứng của nó làm cho nó trở thành một lựa chọn tuyệt vời để phân loại các mảng có độ dài.

Sự kết luận

Sắp xếp là một công cụ thiết yếu trong bất kỳ bộ công cụ Pythonista nào. Với kiến ​​thức về các thuật toán sắp xếp khác nhau trong Python và cách tối đa hóa tiềm năng của chúng, bạn đã sẵn sàng để thực hiện các ứng dụng và chương trình hiệu quả hơn, hiệu quả hơn!

Trong hướng dẫn này, bạn đã học được:

  • Làm thế nào Python sườn tích hợp
     1from random import randint
     2from timeit import repeat
     3
     4def run_sorting_algorithm(algorithm, array):
     5    # Set up the context and prepare the call to the specified
     6    # algorithm using the supplied array. Only import the
     7    # algorithm function if it's not the built-in `sorted()`.
     8    setup_code = f"from __main__ import {algorithm}" \
     9        if algorithm != "sorted" else ""
    10
    11    stmt = f"{algorithm}({array})"
    12
    13    # Execute the code ten different times and return the time
    14    # in seconds that each execution took
    15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
    16
    17    # Finally, display the name of the algorithm and the
    18    # minimum time it took to run
    19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
    
    48 hoạt động đằng sau hậu trường
     1from random import randint
     2from timeit import repeat
     3
     4def run_sorting_algorithm(algorithm, array):
     5    # Set up the context and prepare the call to the specified
     6    # algorithm using the supplied array. Only import the
     7    # algorithm function if it's not the built-in `sorted()`.
     8    setup_code = f"from __main__ import {algorithm}" \
     9        if algorithm != "sorted" else ""
    10
    11    stmt = f"{algorithm}({array})"
    12
    13    # Execute the code ten different times and return the time
    14    # in seconds that each execution took
    15    times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10)
    16
    17    # Finally, display the name of the algorithm and the
    18    # minimum time it took to run
    19    print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
    
    48
    works behind the scenes
  • Ký hiệu O lớn là gì và làm thế nào để sử dụng nó để so sánh hiệu quả của các thuật toán khác nhauBig O notation is and how to use it to compare the efficiency of different algorithms
  • Cách đo thời gian thực tế dành mã của bạnactual time spent running your code
  • Cách thực hiện năm thuật toán sắp xếp khác nhau trong Pythonsorting algorithms in Python
  • Những ưu và nhược điểm của việc sử dụng các thuật toán khác nhaupros and cons are of using different algorithms

Bạn cũng đã học về các kỹ thuật khác nhau như đệ quy, phân chia và chinh phục và ngẫu nhiên. Đây là những khối xây dựng cơ bản để giải quyết một danh sách dài các thuật toán khác nhau và chúng sẽ xuất hiện nhiều lần khi bạn tiếp tục nghiên cứu.recursion, divide and conquer, and randomization. These are fundamental building blocks for solving a long list of different algorithms, and they’ll come up again and again as you keep researching.

Lấy mã được trình bày trong hướng dẫn này, tạo các thử nghiệm mới và khám phá các thuật toán này hơn nữa. Tốt hơn nữa, hãy thử thực hiện các thuật toán sắp xếp khác trong Python. Danh sách này là rộng lớn, nhưng sắp xếp lựa chọn, Heapsort và Sắp xếp cây là ba tùy chọn tuyệt vời để bắt đầu.selection sort, heapsort, and tree sort are three excellent options to start with.

Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự. Xem cùng với hướng dẫn bằng văn bản để hiểu sâu hơn về sự hiểu biết của bạn: Giới thiệu về các thuật toán sắp xếp trong Python This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Introduction to Sorting Algorithms in Python

Chức năng sắp xếp Python có nhanh không?

Thời gian thực hiện Sắp xếp hợp nhất của bạn so với sắp xếp bong bóng và sắp xếp chèn, việc triển khai Sắp xếp hợp nhất là cực kỳ nhanh, sắp xếp mảng mười nghìn phần tử trong chưa đầy một giây!the merge sort implementation is extremely fast, sorting the ten-thousand-element array in less than a second!

Sắp xếp () hoặc sắp xếp () nhanh hơn?

Sắp xếp nhanh hơn 13% so với sắp xếp. .

Sự phức tạp của thời gian là sắp xếp trong Python?

Sắp xếp.Sắp xếp danh sách Python () đã sử dụng thuật toán TIMSORT kể từ phiên bản 2.3.Thuật toán này có độ phức tạp thời gian chạy của O (N.Logn).O(n. logn).

Phương pháp sắp xếp nào là nhanh nhất?

Nếu bạn đã quan sát, độ phức tạp thời gian của QuickSort là O (N logn) trong các trường hợp tốt nhất và trung bình và O (n^2) trong trường hợp xấu nhất.Nhưng vì nó có ưu thế trong các trường hợp trung bình đối với hầu hết các đầu vào, Quicksort thường được coi là thuật toán sắp xếp nhanh nhất trên mạng.Quicksort is O(n logn) in the best and average case scenarios and O(n^2) in the worst case. But since it has the upper hand in the average cases for most inputs, Quicksort is generally considered the “fastest” sorting algorithm.