列表上的Bubblesort-在计算上花费了太多时间

时间:2019-04-01 21:36:02

标签: c++ c++11 bubble-sort stdlist

我创建了一个代码,负责执行列表上的冒泡。它似乎可以工作,但是要花很多时间才能执行。如果有人告诉我问题出在哪里,我会很高兴,这样我就可以避免以后再犯同样的错误

认为可能与auto有关,但是重写代码无济于事。

void Sorting::bubblesort(std::list<int>::iterator start, std::list<int>::iterator stop)
{
    int k = 0;
    int temp;
    std::list<int>::iterator j_1 ;
    for (auto i = start; i != stop; i++)
    {
        for (auto j = std::next(start, 1); j != std::prev(stop, k); j++)
        {
            j_1= std::prev(j, 1);
            if (*j_1 > *j)
            {
                temp = *j_1;
                *j_1 = *j;
                *j = temp;
            }
        }
        k++;
    }
}

经过1000个元素的测试-9,032秒(以std :: chrono测量)

2 个答案:

答案 0 :(得分:2)

void bubblesort(std::list<int>::iterator start, std::list<int>::iterator stop)
{
    std::list<int>::iterator k = stop;
    int temp;
    std::list<int>::iterator j_1 ;
    for (auto i = start; i != stop; i++)
    {
        for (auto j = std::next(start, 1); j != k; j++)
        {
            j_1= std::prev(j, 1);
            if (*j_1 > *j)
            {
                temp = *j_1;
                *j_1 = *j;
                *j = temp;
            }
        }
        k--;
    }
}

为了不一直都在不断地重新计算std::prev(stop, k),您的程序几乎只能这样做

当然,列表也不是存储 int 并对其进行排序的最佳集合


完整示例:

#include <list>
#include <iostream>
#include <chrono>
#include <ctime>

void bubblesort(std::list<int>::iterator start, std::list<int>::iterator stop)
{
#ifdef YOU
    int k = 0;
#else
    std::list<int>::iterator k = stop;
#endif
    int temp;
    std::list<int>::iterator j_1 ;
    for (auto i = start; i != stop; i++)
    {
        for (auto j = std::next(start, 1);
#ifdef YOU
             j != std::prev(stop, k);
#else
             j != k;
#endif
             j++)
        {
            j_1= std::prev(j, 1);
            if (*j_1 > *j)
            {
                temp = *j_1;
                *j_1 = *j;
                *j = temp;
            }
        }
#ifdef YOU
        k++;
#else
        k--;
#endif
    }
}

int main()
{
  std::list<int> l;

  for (int i = 0; i != 1000; ++i)
    l.push_front(i);

#ifdef DEBUG
  for (auto i : l)
    std::cout << i << ' ';
  std::cout << std::endl;
#endif


  std::chrono::time_point<std::chrono::system_clock> start, end;  

  start = std::chrono::system_clock::now();
  bubblesort(l.begin(), l.end());
  end = std::chrono::system_clock::now();
  std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() / 1000.0
    << " sec" << std::endl;

#ifdef DEBUG
  for (auto i : l)
    std::cout << i << ' ';
  std::cout << std::endl;
#endif
}

编译和执行:

pi@raspberrypi:/tmp $ g++  b.cc
pi@raspberrypi:/tmp $ ./a.out
0.183 sec
pi@raspberrypi:/tmp $ g++ -DYOU b.cc
pi@raspberrypi:/tmp $ ./a.out
3.98 sec
pi@raspberrypi:/tmp $ 
pi@raspberrypi:/tmp $ g++ -O3 b.cc
pi@raspberrypi:/tmp $ ./a.out
0.004 sec
pi@raspberrypi:/tmp $ g++ -O3 -DYOU b.cc
pi@raspberrypi:/tmp $ ./a.out
0.413 sec

请注意在O3中进行编译的优势...

答案 1 :(得分:0)

这是bruno答案的附录,最好尝试将sort的实现与实际类型分开,例如

import numpy as np
import matplotlib.pyplot as plt
#plt.rcParams["font.family"] = "Times New Roman"
#plt.rcParams.update({'font.size': 12})

font = {'family' : 'Times New Roman',
        'size'   : 14}  
plt.rc('font', **font)


t = np.linspace(0,10, num=200)
fig, axs = plt.subplots(6, 3, figsize=(12,16))#, constrained_layout=True)
i = 0 # i = 0 for x = 0.25; i = 3 for x = -0.25
j = 6 # j = 6 for x = 0.25; j = 9 for x = -0.25
#%%
solution = np.loadtxt(open("sequential_legs=01.csv", "rb"), delimiter=",", skiprows=0)
axs[0, 0].plot(t, solution[:,i],'r-')
axs[0, 0].plot(t, solution[:,i+1],'g-')
axs[0, 0].plot(t, solution[:,i+2],'b-')
axs[0, 0].plot(t, solution[:,j],'r--')
axs[0, 0].plot(t, solution[:,j+1],'g--')
axs[0, 0].plot(t, solution[:,j+2],'b--')
axs[0, 0].set_title('DNN-S (p = 1)', fontsize=14)
axs[0, 0].set_xlim([0, 10])
(repeated for each grid)
line_labels = ["$y_1$ (True)","$y_2$ (True)", "$y_3$ (True)", "$y_1$ (ML-Pred)","$y_2$ (ML-Pred)", "$y_3$ (ML-Pred)"]
plt.figlegend( line_labels, loc = 'lower center', borderaxespad=0.1, ncol=6, labelspacing=0.,  prop={'size': 13} ) #bbox_to_anchor=(0.5, 0.0), borderaxespad=0.1, 

for ax in axs.flat:
    ax.set(xlabel='Time', ylabel='Response')

for ax in axs.flat:
    ax.label_outer()

fig.savefig('LSE_X=025.pdf', bbox_inches = 'tight')