0% found this document useful (0 votes)
13 views2 pages

Linear Search

Uploaded by

Manav Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views2 pages

Linear Search

Uploaded by

Manav Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

// LINEAR SEARCH

public class LinearSearch {


public static int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}

public static void main(String[] args) {


int[] arr = {3, 5, 7, 9, 11, 15};
int target = 9;
int result = linearSearch(arr, target);
if (result == -1) {
System.out.println("Element not found");
} else {
System.out.println("Element found at index: " + result);
}
}
}

// BINARY SEARCH

public class BinarySearch {


public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

if (arr[mid] == target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return -1;
}

public static void main(String[] args) {


int[] arr = {1, 3, 5, 7, 9, 11, 15};
int target = 7;
int result = binarySearch(arr, target);
if (result == -1) {
System.out.println("Element not found");
} else {
System.out.println("Element found at index: " + result);
}
}
}
// BUBBLE SORT

public class BubbleSort {


public static void bubbleSort(int[] arr) {
int n = arr.length;
boolean swapped;

for (int i = 0; i < n - 1; i++) {


swapped = false;

for (int j = 0; j < n - i - 1; j++) {


if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}

if (!swapped) {
break;
}
}
}

public static void printArray(int[] arr) {


for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}

public static void main(String[] args) {


int[] arr = {5, 1, 4, 2, 8};
System.out.println("Original array:");
printArray(arr);

bubbleSort(arr);

System.out.println("Sorted array:");
printArray(arr);
}
}

You might also like