Linear Search Java program

 class LinearSearch {

    int[] array;

    // Linear search : Time Complexity O(n) and Space Complexity O(1)

    int search(int key) {

        for(int i = 0; i < array.length; i++) {

            if(array[i] == key) {

                return i;

            }

        }

        return -1;

    }

    // Transposition Method : Time Complexity O(n) and Space Complexity O(1)

    int search_improved_transposition(int key) {

        for(int i = 0; i < array.length; i++) {

            if(array[i] == key) {

                if(i > 0) {

                    int temp = array[i-1];

                    array[i-1] = array[i];

                    array[i] = temp;

                    return i-1;

                }

                return i;

            }

        }

        return -1;

    }

    // Move to head Method : Time Complexity O(n) and Space Complexity O(1)

    int search_improved_moveToHead(int key) {

        for(int i = 0; i < array.length; i++) {

            if(array[i] == key) {

               // Move to head

               int temp = array[i];

               array[i] = array[0];

               array[0] = temp;

                return 0;

            }

        }

        return -1;

    }

public static void main (String[] args) {

    LinearSearch obj = new LinearSearch();

    obj.array = new int[] {22, 4,6,3,7,8,43,67,32,87, 56, 77};

    

    System.out.println(obj.search(43));

    System.out.println(obj.search(40));

    

    System.out.println(obj.search_improved_transposition(43));

    System.out.println(obj.search_improved_transposition(40));


    System.out.println(obj.search_improved_moveToHead(43));

    System.out.println(obj.search_improved_moveToHead(40));

}

}


Comments

Popular posts from this blog

SQL basic interview question

gsutil Vs Storage Transfer Service Vs Transfer Appliance