Programming Examples

Java program to search for given item in a given array using liner search if item found then move it at top of array otherwise add at the end of array


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

Solution

import java.util.*;
class items
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter a num");
        int c=sc.nextInt();
        String num[]=new String[c+1];
        int a,b=0,flag=0;

        System.out.println("Enter "+c+" Strings");
        for(a=0;a<c;a++)
        {
            num[a]=sc.next();
        }
        System.out.println("Enter a string to be searched");
        String n=sc.next();
        for(a=0;a<c;a++)
        {
            if(num[a].equalsIgnoreCase(n))
            {
                flag=1;
                b=a;
                break;
            }
        }
        if(flag==1)
        {
        System.out.println("no found at index no.:"+b);
            String temp=num[b];
            for(a=b;a>0;a--)
            {   
               num[a]=num[a-1];               
            }
            num[0]=temp;
            System.out.println("New array:");
        for(a=0;a<c;a++)
        {
            System.out.println(num[a]);
        }
        }
        
        else
        {
        System.out.println("String not found");
        num[c]=n;
        System.out.println("New array:");
        for(a=0;a<(c+1);a++)
        {
            System.out.println(num[a]);
        }
        }
        
    }
}
       
Output

Enter a num

5

Enter 5 Strings

ram

ravi

mohan

kamal

pawan

Enter a string to be searched

mohan

no found at index no.:2

New array:

mohan

ram

ravi

kamal

pawan

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level NIELIT Study material and Quiz Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Website development Company in Allahabad