ICSE Class 10 Computer Applications Question 52 of 71

Arrays — Question 52

Back to all questions
52
Question

Question 46

Write a program to search for a given ITEM in a given array X[n] using linear search technique. If the ITEM is found, move it at the top of the array. If the ITEM is not found, insert it at the end of the array.

import java.util.Scanner;

public class KboatLinearSearch
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter size of array : ");
        int n = in.nextInt();
        
        int X[] = new int[n];
        int B[];
        
        System.out.println("Enter array elements : ");
        for(int i = 0; i < n; i++) {
            X[i] = in.nextInt();
        }

        System.out.println("Enter search item :" );
        int item = in.nextInt();
        
        int i = 0;
        
        // linear search
        for (i = 0; i < n; i++) {
            if (X[i] == item) {
                System.out.println("Search item found at index " 
                                    + i);
                break;
            }
        }
        
        // item not found
        if (i == n) {
            System.out.println("Search item not found");
            B = new int[n + 1];
            for(int j = 0; j < n; j++)  {
                B[j] = X[j];
            }
            B[n] = item;
            
            System.out.println("Array after inserting "
                                + item + " at end:");
            for(int j = 0; j <= n; j++)  {
                System.out.print(B[j] + " ");
            }
        }
        // item found
        else {
            for(int j = i; j >= 1; j--) {
                X[j] = X[j - 1];
            }
            X[0] = item;
                     
            System.out.println("Array after moving " 
                                + item + " to top :");
            for(int j = 0; j < n; j++)  {
                System.out.print(X[j] + " ");
            }
        }   
    }
}
Output
BlueJ output of KboatLinearSearch.java
BlueJ output of KboatLinearSearch.java
Answer