查找是否在数组中存在一个既定的值。

今天试着写了一个C++的。

 

// FindKey.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

///summary
///查找是否在数组中存在一个既定的值。
///二维数组的行值是递增的
///二维数组的列值也是递增的
///返回值是bool型的
///array是传入的二维数组
///rows 是这个数组的行数
/// colums是组数的列数
///key是要查找的值
///summary end
bool FindKey(int* array, int rows, int columns, int key)
{
    int row = 0;
    int column = columns -1;

    bool found = false;///待返回的值

    ///如果数组不为空,并且行列都大于0
    if(array != NULL && columns > 0 && rows > 0)
    {
        ///判断数组不越界
        while (row < rows && column >=0)
        {
            ///如果数组内的值和key相等,给返回值赋值true
            if(array[row * rows + column] == key)
            {
                found = true;
                break;
            }
            ///如果数组的值大于要找的值,列递减
            else if (array[row * rows + column] > key)
            {
                column--;
            }
            ///如果数组的值小于要找的值,行递增
            else
            {
                row++;
            }
        }
    }
    return found;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int array[4][4] = {{1,2,8,9}, {2,4,9,12}, {4,7,10,13}, {6,8,11,15}};

    bool findIt = FindKey(*array, 4, 4, 10);

    cout<<"This is:"<<findIt<<endl;

    cin.get();

    return 0;
}

 

 

写了一个C#的,稍有区别。这次没有写注释。

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FindKeyCS
{
    class Program
    {
        public bool FindKey(int[,] array, int rows, int columns, int key)
        {
            int row = 0;
            int column = columns - 1;
            bool found = false;

            if(array!= null && rows >0 && columns >0)
            {
                while(row < rows && column>=0)
                {
                    if (array[row, column] == key)
                    {
                        found = true;
                        break;
                    }
                    else if (array[row, column] > key)
                    {
                        column--;
                    }
                    else
                    {
                        row++;
                    }
                }
            }
            return found;
        }

        public static void Main(string[] args)
        {
            int[,] intArray = {{1,2,8,9}, {2,4,9,12}, {4,7,10,13}, {6,8,11,15}};

            Program p = new Program();

            bool hasA = p.FindKey(intArray, 4, 4, 0);

            Console.WriteLine(hasA);

            Console.ReadLine();
        }
    }
}

 

posted @ 2014-05-29 14:28  simonzhang  阅读(250)  评论(0编辑  收藏  举报