集册 Java实例教程 int数组线性搜索函数

int数组线性搜索函数

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

402
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
int数组线性搜索函数

class Linear_Search/*来 自 时   代    Java - nowjava.com*/

{

    // Function for linear search

    public static int LinearSearch(int[] array, int size, int desired)

    {

        for(int i = 0; i < size; i++)

        {

            // return position if element is found

            if(array[i] == desired)

                return i;

        }


        return -1;

    }/** n o w j a v a . c o m - 时代Java 提 供 **/


    // Driver Function

    public static void main(String[] args)

    {

        int[] array = {2, 4, 6, 7, 3, 1, 5};


        // Element 4 to be searched

        if(LinearSearch(array, 7, 4) != -1)

            System.out.println("Found");

        else

            System.out.println("Not Found");


        //Element 9 to be searched

        
展开阅读全文