Mergesort vs nlogn曲线(Python)(未获得预期图)

发布于 2025-02-12 14:55:07 字数 2113 浏览 0 评论 0原文

我正在尝试在对N元素与NLOGN进行排序的合并排序的执行时间之间绘制图形,但是我没有得到预期的图形。

from random import randint
from math import log2
import timeit
import matplotlib.pyplot as plt


def merge(arr, l, m, r):
    n1 = m - l + 1
    n2 = r - m
    L = [0] * (n1)
    R = [0] * (n2)
    for i in range(0, n1):
        L[i] = arr[l + i]
    for j in range(0, n2):
        R[j] = arr[m + 1 + j]

    i = 0    # Initial index of first subarray
    j = 0    # Initial index of second subarray
    k = l    # Initial index of merged subarray

    while i < n1 and j < n2:
        if L[i] <= R[j]:
            arr[k] = L[i]
            i += 1
        else:
            arr[k] = R[j]
            j += 1
        k += 1

    # Copy the remaining elements
    while i < n1:
        arr[k] = L[i]
        i += 1
        k += 1

    # Copy the remaining elements
    while j < n2:
        arr[k] = R[j]
        j += 1
        k += 1


def mergeSort(arr, l, r):
    if l < r:
        m = l+(r-l)//2
        mergeSort(arr, l, m)
        mergeSort(arr, m+1, r)
        merge(arr, l, m, r)


arr = []
x = []
y = []
n = []
for i in range(1, 3000, 100):
    for j in range(i):
        temp = randint(0, i)
        arr.append(temp) # making a array of random int values
    x.append(i)
    start = timeit.default_timer()
    mergeSort(arr, 0, i-1)
    end = timeit.default_timer()
    y.append(end - start) # storing the execution time to sort the array
    n.append(i*log2(i)) # Calculating nlogn

plt.plot(x, y, label='merge sort')
plt.plot(x, n, label='nlogn')
plt.legend()
plt.xlabel('array size ')
plt.ylabel('execution time (s)')
plt.title('Merge Sort')
plt.show()

该程序的输出:

“在此处输入图像描述”

例外的输出:

我们知道,合并排序算法的时间复杂性是o(nlogn),但是当我试图尝试绘制它非常低。

请建议我一种绘制图形或此代码中一些修改的方法。

I am trying to plot a graph between the execution time of merge sort for sorting n elements vs nlogn but I am not getting the expected graph.

from random import randint
from math import log2
import timeit
import matplotlib.pyplot as plt


def merge(arr, l, m, r):
    n1 = m - l + 1
    n2 = r - m
    L = [0] * (n1)
    R = [0] * (n2)
    for i in range(0, n1):
        L[i] = arr[l + i]
    for j in range(0, n2):
        R[j] = arr[m + 1 + j]

    i = 0    # Initial index of first subarray
    j = 0    # Initial index of second subarray
    k = l    # Initial index of merged subarray

    while i < n1 and j < n2:
        if L[i] <= R[j]:
            arr[k] = L[i]
            i += 1
        else:
            arr[k] = R[j]
            j += 1
        k += 1

    # Copy the remaining elements
    while i < n1:
        arr[k] = L[i]
        i += 1
        k += 1

    # Copy the remaining elements
    while j < n2:
        arr[k] = R[j]
        j += 1
        k += 1


def mergeSort(arr, l, r):
    if l < r:
        m = l+(r-l)//2
        mergeSort(arr, l, m)
        mergeSort(arr, m+1, r)
        merge(arr, l, m, r)


arr = []
x = []
y = []
n = []
for i in range(1, 3000, 100):
    for j in range(i):
        temp = randint(0, i)
        arr.append(temp) # making a array of random int values
    x.append(i)
    start = timeit.default_timer()
    mergeSort(arr, 0, i-1)
    end = timeit.default_timer()
    y.append(end - start) # storing the execution time to sort the array
    n.append(i*log2(i)) # Calculating nlogn

plt.plot(x, y, label='merge sort')
plt.plot(x, n, label='nlogn')
plt.legend()
plt.xlabel('array size ')
plt.ylabel('execution time (s)')
plt.title('Merge Sort')
plt.show()

Output of this program:

enter image description here

Excepted output:

enter image description here

As we know that the time complexity of merge sort algorithm is O(nlogn), but when i am trying to plot it it's very low.

Please suggest me a method to plot the graphs or some modification in this code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

百变从容 2025-02-19 14:55:07

小阵列的时间差异将受小组拟合的高速缓存水平的影响。即使对于大型数组,缓存也会影响排序时间,而不是计算操作数量(比较和移动)。还有Python的开销,对于同一合并排序算法,超过50倍的速度是C或C ++实现的速度。对于大N ) / log2(2^20)= 1.05,log2(2^26) / log2(2^25)= 1.04,等等。

Differences in time for small arrays will be affected by the level of cache a small array fits into. Even for large arrays, cache will affect sort times as opposed to counting the number of operations (compares and moves). There's also the overhead of Python, over 50 times as slow as a C or C++ implementation for the same merge sort algorithm. For large n, the number of operations approaches O(n), since log2(2n)/log2(n) approaches 1. For example log2(2^11) / log2(2^10) = 1.10, log2(2^21) / log2(2^20) = 1.05, log2(2^26) / log2(2^25) = 1.04, and so on.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文