这个c ++程序如何更快?

时间:2017-12-15 08:05:06

标签: c++ arrays sorting

以下是该计划的链接:http://gpe.acm-icpc.tw/domjudge2/pct/showproblemtab.php?probid=10527&cid=5

这是我迄今为止所完成的工作:

首先,我创建了一个函数,它将对下面代码中的ord(a,j)数组进行排序。

变量j是每次用户输入数字时将递增的数组的大小。

为了计算中位数,我有两个案例。

1)如果数组的大小是偶数,那么我将数组的大小减去1并除以2,然后结果将是排序数组的索引加上排序数组的下一个元素用2来找到中位数。

例如:{1,3,6,2,7,8}个元素的数组。我将首先对数组进行排序,它将给出:{1,2,3,6,7,8}然后中位数将是(3 + 6)/ 2 = 4.

2)如果数组的大小是奇数,那么我将排序数组的大小减去1并除以2,结果是中位数的索引。

例如:{1,3,7,2,5}个元素的数组。我将首先对数组进行排序,然后给出:{1,2,3,5,7},然后中位数为3.

      int* ord(int A[], int n) // function to sort the array
     {
           for(int i = 0; i < n; i++)
         {
            for(int v = 0;  v < n -1; v++)
            {
              if(A[v] > A[v+1])
            {
              swap(A[v], A[v+1]); 
            }
          }
        }

        return A; 
      } 


  int main()
  {
    int a[N], x, j = 0, c; 



      while(cin >> x)
     {

       j++; // This is the size of the array


       a[j-1]=x; 

       // Below is the algorithm for finding the median


      if (j == 1) // if the array contains only one value, I just output the value
     {
      cout << a[0] << endl; 
     }
     else // if it contains more than one value then I compute the median
     { 

      ord(a, j); //sorted array 

      if (j % 2 == 0) // first case is when the size of the array is even
      { 
         // First I subtract the size of the array by 1 and divide it by 2, then c will be the index of the sorted array plus the next element of the sorted array divided by 2 to find the median

        c = (j-1) / 2; 

          cout << (a[c] + a[c+1]) / 2 << endl;
      }
      else // second case when the size of the array is odd
      {
         // First I subtract the size of the array by 1 and divide it by 2, c will be the index of the median

        c = j-1; 

        cout << a[c / 2] << endl; 
      } 

    }


  }


}

2 个答案:

答案 0 :(得分:1)

使用std :: vector来保存你的整数。然后在它上面使用std :: sort。如果您必须编写自己的排序,请尝试实现快速排序或mergsort。

这是一个通过vector和std :: sort进行快速排序。

  int array_size = 8;
  int myints[] = {32,71,12,45,26,80,53,33};
  std::vector<int> myvector (myints, myints+array_size);               
  std::sort (myvector.begin(), myvector.end());           

如果您需要了解更快的排序算法:

https://en.wikipedia.org/wiki/Quicksort

https://en.wikipedia.org/wiki/Merge_sort

一般的想法是对数组的某些部分进行某种预分类,然后对所有内容进行排序。这使得运行时log(n) n而不是n n。这是一个主要的加速,甚至更多的数字上升。例如:

log(1024)* 1024 = 10 * 1024 = 10.240操作。

1024 * 1024~1.000.000操作&lt; - 慢100倍

log(1.000.000)* 1.000.000 = 20 * 1.000.000 = 20.000.000操作。

1.000.000 * 1.000.000 = 1.000.000.000.000操作&lt; - 50.000倍慢

答案 1 :(得分:1)

我认为你做错了。 首先,你不应该在循环内调用排序函数,它每次都做同样的工作,并增加时间。在while循环结束后调用它就足够了。这将大大加快您的计划。

同样在while循环中,你首先增加了j的值,然后你已经分配了

a[j-1] = x;

你应该先分配

a[j] = x; 然后j++;

,因为

a[j-1] = x; // here j-1 will take some fraction of milliseconds to calc [j-1]

希望你的程序能加快速度。