这个C++程序如何更快?
以下是程序的链接: 以下是我迄今为止所做的工作: 首先,我创建了一个函数,该函数将对数组进行排序,在下面的代码中是orda,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这个C++程序如何更快?,c++,arrays,sorting,C++,Arrays,Sorting,以下是程序的链接: 以下是我迄今为止所做的工作: 首先,我创建了一个函数,该函数将对数组进行排序,在下面的代码中是orda,j 变量j是数组的大小,每当用户输入一个数字时,该数组将递增 为了计算中位数,我有两种情况 1如果数组的大小是偶数,那么我将数组的大小减去1,再除以2,结果将是排序数组的索引加上排序数组的下一个元素除以2得到中值 例如:{1,3,6,2,7,8}元素的数组。我将首先对数组进行排序,它将给出:{1,2,3,6,7,8},然后中值将是3+6/2=4 2如果数组的大小是奇数,那么
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;
}
}
}
}
使用std::vector保存整数。然后对其使用std::sort。如果必须编写自己的排序,请尝试实现快速排序或mergsort 这是通过向量和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());
如果您需要了解更快的排序算法:
总体思路是对数组的某些部分进行某种预排序,然后对所有内容进行排序。这将使运行时lognn代替nn。这是一个重大的提速,数字上升得越大,速度就越快。例如:
log1024*1024=10*1024=10.240操作
1024*1024~1.000.000次手术我认为你做错了。 首先,您不应该在循环内调用排序函数,它每次都做相同的工作,并且会增加时间。在while循环结束后调用一次就足够了。这将大大加快您的程序 同样在while循环中,首先增加j的值,然后分配 a[j-1]=x 你应该先分配 a[j]=x; 然后是j++ 因为 a[j-1]=x;//这里,j-1需要几毫秒来计算[j-1]
希望你的程序能加快速度 使用更好的排序算法从简化一点开始。用于排序使用,用于获取中值使用。另外,不要链接到代码。把代码放在问题中。我应该使用哪种更好的排序算法@lamandy?如果您使用STL容器,如std::array或std::vector,std::sort就可以了。如果您想实现自己的,请查看快速排序和合并排序。该链接的访问受到限制。。。