如何优化此函数(初学者)JAVA

如何优化此函数(初学者)JAVA,java,arrays,performance,Java,Arrays,Performance,我有此功能,需要对其进行优化,以减少运行时间: public static int recherche(int cherche, int[] t) { int srch = 0; int tmp=0; boolean result = false; for (int i=0; i<t.length ; i++) { if (t[i]== cherche && result == false) { tmp

我有此功能,需要对其进行优化,以减少运行时间:

public static int recherche(int cherche, int[] t) {
    int srch = 0;
    int tmp=0;
    boolean result = false;
    for (int i=0; i<t.length ; i++) {
        if (t[i]== cherche && result == false) {
            tmp++;
            srch = i;
            result=true;
        }
    }       
    if (tmp!=0) { 
        return srch ;
    }
    else { 
        return -1;
    }
}
公共静态int-recherche(int-cherche,int[]t){
int srch=0;
int-tmp=0;
布尔结果=假;

对于(inti=0;i来说,您可以做的优化是在找到结果后立即返回结果并删除冗余变量

public static int research(int searched, int[] t) {
    for (int i=0; i < t.length ; i++) {
        if (t[i] == searched) {
            return i;
        }
    }
    return -1;
}

public static int recherche(int cherche, int[] t) {
    int srch = -1;
    for (int i = 0; i < t.length; i++) {
        if (t[i] == cherche) {
            srch = i;
            break;
        }
    }       
    return srch;
} 
publicstaticint研究(int搜索,int[]t){
对于(int i=0;i
如果我正确理解了您的方法,您正在搜索数组
t
中第一次出现的
cherche
的索引,如果没有找到,则搜索-1

代码的问题是,即使已经找到条目,也会继续循环。最好立即中断循环。您也不需要额外的变量

public static int research(int searched, int[] t) {
    for (int i=0; i < t.length ; i++) {
        if (t[i] == searched) {
            return i;
        }
    }
    return -1;
}

public static int recherche(int cherche, int[] t) {
    int srch = -1;
    for (int i = 0; i < t.length; i++) {
        if (t[i] == cherche) {
            srch = i;
            break;
        }
    }       
    return srch;
} 
公共静态int-recherche(int-cherche,int[]t){
int srch=-1;
对于(int i=0;i
如果这仍然太慢,您可以尝试存储已排序的数据或创建某种索引

如果您有一个列表而不是数组,您可以使用该方法,但我认为对于未排序的数据,它不会更快。 它总是
O(n)
,因为您必须在最坏的情况下检查所有数组值


S:请考虑使用更好的变量名。我不知道什么是<代码> T < /C>和<代码> CelChe< /Cord>是。

< P>在java中没有这个函数可以进行真正的优化。如果知道数组<代码> t>代码>,可以使用二进制排序。< /p> 不过我把你的代码整理了一下

public static int recherche(int cherche, int[] t) {
    for (int i = 0; i < t.length; i++) {
        if (t[i] == cherche) {
            return i;
        }
    }

    return -1;
}
公共静态int-recherche(int-cherche,int[]t){
对于(int i=0;i
看来“cherche”是法语中“seek”的意思。感谢您的帮助,在找到索引时爆发大大减少了时间。同时,对于首次出现在此处的变量名,也很抱歉。请添加此程序尝试执行的操作、输入内容以及预期结果的说明。您为什么认为这花费的时间太长?如果您只是在查找第一个匹配项,那么在找到匹配项后,您希望中断for循环。是的,很抱歉缺少描述,因此这是在搜索t中第一次出现的cherche的索引,如果没有找到,则返回-1。此外,这是一个类练习,我们得到了一个表示它在图形中所用时间的函数。