集册 Java实例教程 对给定数组中的整数执行线性搜索。

对给定数组中的整数执行线性搜索。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

418
对给定数组中的整数执行线性搜索。

/*

 * Copyright (C) 2013 Marten Gajda <marten@dmfs.org>

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 * 

 */

//package com.nowjava;
//from 时 代 J a v a

public class Main {

    /**

     * Perform a linear search for an integer in a given array. For small fields a linear search can be faster than a binary search. So use this if you know

     * your field contains only few entries.

     * 

     * @param array

     *            The array to search (the hay stack). Must not be <code>null</code>!

     * @param i

     *            The value to search for (the needle).

     * @return the position of the value in the array or <code>-1</code> if the value has not been found.

     */

    public static int linearSearch(int[] array, int i) {

        for (int c = 0, len = array.length; c < len; ++c) {

            if (array[c] == i) {

                return c;

            }

        }

        return -1;

    }


    /**

     * Perform a linear search for a long in a given array. For small fields a linear search can be faster than a binary search. So use this if you know your

     * field contains only few entries.

     * 

     * @param array

     *            The array to search (the hay stack). Must not be <code>null</code>!

     * @param l

     *            The value to search for (the needle).

     * @return the position of the value in the array or <code>-1</code> if the value has not been found.

     */

    public static int linearSearch(long[] array, long l) {

        return linearSearch(array, 0, array.length, l);

    }
// from N  o w  J a v a . c o m

    
展开阅读全文