当前位置: 动力学知识库 > 问答 > 编程问答 >

java - C# array indexing

问题描述:

Apology in advance if this is an obvious question.

I just switched from java to C# and I am doing practice in C# in order to get myself familiar with it.

It's just a binary search program.

  1. there is an error in this line key > array[mid]

    cannot apply indexing with [] to an expression of type system.array.

  2. I tried to google it and someone said it should be key > array.GetValue(mid),but after changing it the error becomes "Operator < cannot be applied to operands of type int and object".

I really don't know what to do and I don't have anybody to discuss it, so any help or any advice about switching from java to C# would be great. Thanks.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace BinarySearch.BinarySearch

{

class BinarySearch

{

public int BinarySearch(int key, Array array)

{

int lowerbound = 0, upperbound = array.Length, mid = 0, count = 0, midValue = 0;

while (lowerbound <= upperbound)

{

mid = (lowerbound + upperbound)>>1;

if (key < array[mid])

{

upperbound = mid - 1;

count++;

}

else if (key > array[mid])

{

lowerbound = mid + 1;

count++;

}

else

{

count++;

return mid;

}

}

return -1; //the key does not exist in this array.

}

}

}

网友答案:

If you really want to use the type Array in your code, you can use the GetValue() method, but you need to cast the returned object instance back to int to compare it. E.g.:

if (key < (int)array.GetValue(mid))

But that's probably not what you actually want. You should be using the array the same way you use it in Java. E.g.:

public int BinarySearch(int key, int[] array)

then you can write expression exactly as you would in Java:

if (key < array[mid])

Finally, a couple of other things:

  1. Your code returns an Array, which doesn't make any sense. I changed the return type in the above example to int
  2. .NET already has a perfectly good binary search implementation. One hopes this is just for your own edification, rather than something used in production code somewhere. :)
分享给朋友:
您可能感兴趣的文章:
随机阅读: