0% found this document useful (0 votes)
11 views

Sorting and Searching

The document discusses various sorting and searching algorithms like linear search, binary search, bubble sort, selection sort and linear search for 2D arrays. It includes code implementations of these algorithms in Java.

Uploaded by

dhruv manshani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Sorting and Searching

The document discusses various sorting and searching algorithms like linear search, binary search, bubble sort, selection sort and linear search for 2D arrays. It includes code implementations of these algorithms in Java.

Uploaded by

dhruv manshani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Saturday, July 29, 2023

Sorting And Searching

Computer Applications

//LINEAR SEARCH
import java.util.*;

class D{
void main(){

int A[] = new int[5];


Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of array");
int n = sc.nextInt();

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

for(int i = 0;i<n;i++){
A[i] = sc.nextInt();
}

System.out.println("Enter the number you want to check");


int b = sc.nextInt();
for(int j = 0;j<n;j++){
if(A[j]==b){
System.out.println("The element is present");
break;
}else{
System.out.println("The element is not present");
}
}

}
}

1

//Binary Search
import java.util.*;

class Binary{
void main(){
int A []= new int[50];
Scanner sc = new Scanner(System.in);
System.out.println("Enter the array size");
int n= sc.nextInt();
System.out.println("enter the element to check");
int search = sc.nextInt();

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


for(int i = 0;i<search;i++){
A[i] = sc.nextInt();
}

int l = 0;
int u = n-1;
int m = 0;
int p = 0;

while(l<=u){
m = (l+u)/2;

if(search>A[m])
l = m+1;

else if(search<A[m])
u = m-1;
else{
p++;
break;
}
if(p>0)
System.out.println("element found at position"+(m+1));
else
System.out.println("Element is not in the list");

}
}

2

//Bubble Sort
class Array1{
void main(){
int a[] = {15,25,2,45,9};
int t;
for(int i = 0;i<5;i++){
for(int j = 0;j<5-i-1;j++){
if(a[j]>a[j+1]){
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}

for(int i = 0;i<5;i++){
System.out.print(a[i]+" ");
}
}
}

3

//Selection Sort
import java.util.*;

class Ma{
void main(){
int a[] = {15,3,5,8,32};
int t;
for(int i = 0;i<5;i++){
int min = i;
//finding minimum
for(int j = i+1;j<5;j++){
if(a[j]<a[min]){
min = j;
}
}

//Substitution
t = a[i];
a[i] = a[min];
a[min] = t;
}
}
}

4

//Linear Search for 2d Array
import java.util.*;

class Ma{
void main(){
int a[][] = new int[3][3];
Scanner sc = new Scanner(System.in);
for(int i = 0;i<3;i++){
for(int j = 0;j<3;j++){
a[i][j] = sc.nextInt();
}
}
int n = sc.nextInt();
for(int i = 0;i<3;i++){
for(int j = 0;j<3;j++){
if(n==a[i][j]){
System.out.println("Element found");
break;
}
}
}

}
}

5

You might also like