Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/149.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我是不是把这个伪代码解释错了?_C++_Algorithm_Array Algorithms - Fatal编程技术网

C++ 我是不是把这个伪代码解释错了?

C++ 我是不是把这个伪代码解释错了?,c++,algorithm,array-algorithms,C++,Algorithm,Array Algorithms,我有一个伪代码: COMPARE-EXCHANGE(A,i,j) if A[i] > A[j] exchange A[i] with A[j] INSERTION-SORT(A) for j = 2 to A.length for i = j-1 downto 1 COMPARE-EXCHANGE(A,i,i+1) 我将其解释为: void insertSort( ) { int tmp; for

我有一个伪代码:

COMPARE-EXCHANGE(A,i,j)
    if A[i] > A[j]
        exchange A[i] with A[j]

INSERTION-SORT(A)
    for j = 2 to A.length
        for i = j-1 downto 1
            COMPARE-EXCHANGE(A,i,i+1)
我将其解释为:

void insertSort( )
{
    int tmp;

    for( int j = 2 ; j < MAX ; ++j )
    {
        for( int i = j - 1 ; i > 0 ; --i )
        {
            if( unsortedArr[i] > unsortedArr[i + 1] )
            {
                tmp                 = unsortedArr[i];
                unsortedArr[i]      = unsortedArr[i + 1];
                unsortedArr[i + 1]  = tmp;
            }
        }
    }
}
将使其按预期运行。
在伪代码中有错误吗?还是我第一次尝试解释它错误?

< p>我认为你的伪代码假设数组从索引一开始[1 ] -在C++ C++中它们从零开始[0 ]。 但是,这将跳过反排序[0]。这意味着它不会起作用

伪代码从1开始对数组元素进行编号几乎是通用的,而不是像C/C中那样从零开始++

将的第二个更改为:

对于(int i=j-1;i>=0;--i)

将使其按预期运行

这还不够:您还需要在外部循环的
1
处启动
j
,而不是
2

< P>还注意到C++标准库提供了 STD::SWAP/<代码>函数,它负责为您交换数组的元素:

if( unsortedArr[i] > unsortedArr[i + 1] )
{
    std::swap(unsortedArr[i], unsortedArr[i+1]);
}

伪代码很可能使用1个索引数组,而C++数组中的索引是0个索引。
if( unsortedArr[i] > unsortedArr[i + 1] )
{
    std::swap(unsortedArr[i], unsortedArr[i+1]);
}