Search code examples
javasearchsequential

sequential search backward


I am learning sequential search and have sequential search codes but I want to find numbers whose search process is from right (end of data) to left (beginning of data).

public static void main(String[] args) {
        int []a={5,6,9,2,8,1,7};
        int key=8;
        boolean f=false;
        for (int i = 0; i < a.length; i++) {
            if(key == a[i]){
                System.out.println("data found on index "+i);
                f=true;
                break;
            }
        }
        if (f=false){
            System.out.println("data not found");
        }
    } 

Solution

  • If you want to search from back to front, I think you can just edit for loop option.
    for (int i = a.length - 1 ; i >= 0; i--)