zoukankan      html  css  js  c++  java
  • C# 已排序好的数组中查找数的位置

            static int FindNumber(int[] array, int num)
    {
    int result = -1;
    if (array == null)
    {
    return result;
    }

    for (int i = 0; i < array.Length - 1; i++)
    {
    if (array[i] > array[i + 1])
    {
    throw new Exception("input array is not sorted properly.");
    }
    }

    for (int j = 0; j < array.Length; j++)
    {
    if (array[j] == num)
    {
    result = j;
    }
    }
    return result;
    }

    static int FindNumber1(int[] array, int num)
    {
    int result = -1;
    if (array == null)
    {
    return result;
    }
    for (int i = 0; i < array.Length -1; i++)
    {
    if (array[i] > array[i +1])
    {
    throw new Exception("input array is not softed properly.");
    }
    }

    int low = 0;
    int mid = 0;
    int high = array.Length - 1;

    while (low<=high)
    {
    mid = (low + high) / 2;
    if (array[mid] == num)
    {
    result = mid;
    break;
    }
    if (array[mid] < num)
    {
    low = mid + 1;
    }
    else
    {
    high = mid - 1;
    }
    }
    return result;
    }

    测试用例

    {1,2,3,4}, 3

    {1,2,3,4}, 5

    {1,2,3,4}, 1

    {1,2,3,4}, 4

    {2,1,3,4}, 3

    {2,1,3,4}, 0

    null , 1

    {}, 1

    {1,2,3........999...} ,  323

  • 相关阅读:
    我罗斯方块最终篇
    我罗斯汇报作业一
    11组-Alpha冲刺-2/6
    11组-Alpha冲刺-1/6
    结对编程作业
    11组 团队展示
    第一次个人编程作业
    第一次博客作业
    寒假作业3
    寒假作业2
  • 原文地址:https://www.cnblogs.com/Ligeance/p/2395984.html
Copyright © 2011-2022 走看看