检查二维数组的每个元素是否按升序排序

时间:2018-02-03 13:59:02

标签: arrays sorting multidimensional-array puzzle

实际上我试图制作一个数字益智游戏,你必须将洗牌后的数字移动到空白区域,最终按升序排列所有15个数字。我可以玩和订购游戏的所有数字,但是当检查所有数字是否按升序排序时,即从1到15,我没有得到所需的结果。这是完成检查并公布结果的游戏的最后一部分。我尝试了很多,最后我最终输入了愚蠢的if else条件。 我不想要现成的代码,一个小的提示或程序将不胜感激。

/*My two dimensional array is of 4 * 4 dimension.
Initially to test whether all the elements are sorted in ascending order or 
not
I took a casual approach, the same we use in for one dimensional array.*/

for(int i = 0; i < row; i++) //row = 4
{
    for(int j = 0; j < col; j++) // col = 4
    {
        int k = j + 1;
        if(k != 4)
        {
            if(array[i][j] < array[i][k])
                continue;
        }
    }
}

/*But this above code isn't the right code because it checks whether each 
 and every row is correctly sorted or not
 So even if my output is 
 1 2 3 4
 5 6 7 8
 9 10 13 14
 11 12 15 _ 
 it will say game completed or you have won whereas my expected output was 
 this 
 1 2 3 4
 5 6 7 8
 9 10 11 12
 13 14 15 _  ***UNDERSCORE SIGN IS MEANT FOR BLANK SPACE */`

1 个答案:

答案 0 :(得分:0)

如果您不使用VB,那么这将是伪代码:

Function ArrayIsOrdered(arr(,) As Integer) As Boolean
    Dim xSize = arr.GetUpperBound(0)
    Dim ySize = arr.GetUpperBound(1)

    ' set a temporary variable to the lowest possible value
    Dim x = Integer.MinValue

    ' iterate over the array
    For j = 0 To ySize
        For i = 0 To xSize
            ' if this value is less than the previous value
            ' then the array is not in order
            If arr(i, j) < x Then
                Return False
            End If
            ' save this value for the next comparison
            x = arr(i, j)
        Next
    Next

    ' everything must have been in order
    Return True

End Function

以撇号开头的行是注释。

您需要确定您正在使用的数组维度。

如果你对未占用的方块有一个魔法值,那么当然你需要忽略具有该值的单元格。