Experiment 1 Java
Experiment 1 Java
1.LINEAR SEARCH:
import java.util.Scanner;
public class LinearSearch {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter the array elements:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
System.out.print("Enter the element to search for: ");
int x = scanner.nextInt();
int position = -1;
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
position = i;
break;
}
}
if (position != -1) {
System.out.println("Element found at position " + (position + 1));
} else {
System.out.println("Element not found in the array");
}
scanner.close();
}
}
Output:
Enter the number of elements in the array: 3
Enter the array elements:
50
12
13
Enter the element to search for: 12
Element found at position 1
2.BINARY SEARCH
import java.util.Scanner;
public class BinarySearch {
public static void main(String[] args) {
Output:
Enter the no of elements in an array: 5
Enter the array elements in sorted order:1
2
3
4
5
Enter the search element: 5
Element found at index 4
3.SELECTION SORT
import java.util.Scanner;
public class SelectionSort {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in an array: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter the array elements:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
int temp = arr[i];
arr[i] = arr[minIdx];
arr[minIdx] = temp;
}
System.out.println("Sorted Array elements:");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
scanner.close();
}
}
Output:
Enter the number of elements in an array: 3
Enter the array elements:
12
15
30
Sorted Array elements:
12 15 30
4.INSERTION SORT
import java.util.Scanner;
public class InsertionSort {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in an array: ");
int n = scanner.nextInt();
Output:
Enter the number of elements in an array: 4
Enter the array elements:
12
15
16
18
Sorted Array elements:
12 15 16 18