Arrays Programs

Java Program to find an elements using Linear Searching Techniques.

import java.util.Scanner;

class LinearSearch

{

public static void main()

{

int c, n, search;

Scanner in = new Scanner(System.in);

System.out.println("Enter number of elements");

n = in.nextInt();

int array[] = new int[n];

System.out.println("Enter integers");

for (c = 0; c < n; c++)

array[c] = in.nextInt();

System.out.println("Enter value to find");

search = in.nextInt();

for (c = 0; c < n; c++)

{

if (array[c] == search) /* Searching element is present */

{

System.out.println(search + " is present at location " + (c + 1) + ".");

break;

}

}

if (c == n) /* Element to search isn't present */

System.out.println(search + " isn't present in array.");

}

}

Java program to sort the Array elements using bubble sort

import java.util.Arrays;

import java.util.*;


public class BubbleSort

{

public static void main()

{

int i,j,size;

int a[]=new int[5];

Scanner sc=new Scanner (System.in);

size=a.length;

System.out.println("Enter 5 elements");

for(i=0;i<size;i++)

{

a[i]=sc.nextInt();

}

System.out.println("Array before sorting " + Arrays.toString(a));

int temp;

for(i=0;i<a.length;i++)

{

for(j=1;j<size-i;j++)

{

if(a[j-1]>a[j])

{

temp=a[j-1];

a[j-1]=a[j];

a[j]=temp;

}

}

System.out.println((i+1) +"th elements swapped" + Arrays.toString(a));


}

System.out.println("Values after Bubble sort " + Arrays.toString(a));

}

}


Java program to sort the elements using selection sort.

import java.util.Arrays;

import java.util.*;


public class SelectionSort

{

public static void main()

{

int i,j,size,k, temp;

int a[]=new int[5];

Scanner sc=new Scanner(System.in);

System.out.println("Enter the array elements");

for(i=0;i<a.length;i++)

{

a[i]=sc.nextInt();

}

System.out.println("Sorting of elements using Selection sort");

for(j=0;j<a.length;j++)

{

for(k=j+1;k<a.length;k++)

{

if(a[j]>a[k])

{

temp=a[j];

a[j]=a[k];

a[k]=temp;

}

}

System.out.println((j+1) +"th elements swapped" + Arrays.toString(a));


}

System.out.println("Values after sorting");

for(i=0;i<a.length;i++)

{

System.out.print(a[i] + " ");

}

}

}