0% found this document useful (0 votes)
8 views10 pages

Ex 1 Oops

The document describes four different Java programs that implement various search and sorting algorithms: Sequential Search, Binary Search, Selection Sort, and Insertion Sort. Each section includes the aim, algorithm steps, program code, and output results. The programs demonstrate how to manipulate arrays to find elements or sort them using the respective algorithms.

Uploaded by

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

Ex 1 Oops

The document describes four different Java programs that implement various search and sorting algorithms: Sequential Search, Binary Search, Selection Sort, and Insertion Sort. Each section includes the aim, algorithm steps, program code, and output results. The programs demonstrate how to manipulate arrays to find elements or sort them using the respective algorithms.

Uploaded by

dhanavin2025
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

[Link].

A DATE: SEQUENTIALSEARCH

Aim
To write a Java program to solve problems in array by using sequential search
algorithm.

Algorithm:
1. Start the program
2. Create Sequential Search class with one dimensionalarray.
3. Read the search element from the user.
4. Compare the search element with the first element in the list
5. If both are matched,then display"Given element is found!!!"and terminate the function
6. If both are not matched, then compare search element with the next element in the list.
7. Repeat steps3 and 4 until search element is compared with last element in the list.
8. If last element in the list also doesn't match, then display "Element is not found!!!"and
terminate the function.
9. Stop the program.

Program:
public class Main {
public static void main(String[] args) {
int[] one = {2, 9, 6, 7, 4, 5, 3, 0, 1};
int target = 4;
sequentialSearch(one, target);
}

public static void sequentialSearch(int[] a, int b) {


int index = -1;
for (int i = 0; i < [Link]; i++) {
if (a[i] == b) {
index = i;
break;
}
}
if (index == -1) {
[Link]("Your target does not exist in the array");
} else {
[Link]("Your target is at index " + index + " of the array");
}
}
}

7
Output:

Your target integer is in index 4 of the array

7
[Link].B DATE: BINARYSEARCH

Aim
To write a Java program to solve problems in array by using binary search algorithm.

Algorithm

1. Start the program


2. Create Binary Search class with one dimensional array.
3. Read the search element from the user.
4. Find the middle element in the sorted list.
5. Compare the search element with the middle element in the sorted list.
6. If both are matched, then display" Given element is found!!!"and terminate the function.
7. If both are not matched, then check whether the search element is smaller or larger than the middle element.
8. If the search element is smaller than middle element, repeat steps 2,3,4 and5 for the left sub list of the middle
element.
9. If the search element is larger than middle element, repeat steps 2, 3, 4 and5 for the right sub list of the middle
element.
10. Repeat the same process until we find the search element in the list or until sub list contains only one element.
11. If that element also doesn't match with the search element, then display" Element is not found in the list!!!" and
terminate the function.
12. Stop the program.

Program:
class BinarySearch {
public static int binarySearch(int arr[], int first, int last, int key) {
if (last >= first) {
int mid = first + (last - first) / 2;

if (arr[mid] == key) {
return mid;
}

if (arr[mid] > key) {


// search in left subarray
return binarySearch(arr, first, mid - 1, key);
} else {
// search in right subarray
return binarySearch(arr, mid + 1, last, key);
}
}

return -1; // key not found


}

public static void main(String args[]) {


7
int arr[] = {10, 20, 30, 40, 50};
int key = 30;
int last = [Link] - 1;

int result = binarySearch(arr, 0, last, key);

if (result == -1)
[Link]("Element is not found!");
else
[Link]("Element is found at index: " + result);
}
}

Output:

Element is found at index: 2

7
[Link].C. DATE: SELECTIONSORT

Aim:
To write a Java program to solve problems in array by using selection sort algorithm.

Algorithm:
1. Start the program.
2. Create a SelectionSort class with one dimensional array.
3. Select the first element of the list(i.e.,Element atfirstpositioninthelist).
4. Compare the selectedelement withall the other eleents in the list.
5. In every comparision, if any element is found smaller than the select ed element (for
Ascending order), then both are swapped.
6. Repeat the same procedure with elemnt in then ext position in the list till the entire list is
sorted.
7. Stopthe program

Program:
public class SelectionSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 3};

// Selection Sort
for (int i = 0; i < [Link] - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < [Link]; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}

// Swap arr[i] and arr[minIndex]


int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}

// Print sorted array


[Link]("Sorted array:");
for (int num : arr) {
[Link](num + " ");
}
}
}

7
OUTPUT:
Sorted array:
12358

Result:
Thus the program for solving problems in array using selectionsort algorithm has
been Executed and the output was verified.

[Link].D DATE: INSERTIONSORT

Aim
TowriteaJavaprogramtosolveproblemsinarraybyusinginsertionsortalgorithm.

7
Algorithm

1. Starttheprogram.
2. CreateaInsertionSortclasswithonedimensional array.
3. Assumethatfirstelementinthelistisinsortedportionandalltheremainingelementsarein unsorted
portion.
4. Takefirstelementfromtheunsortedportionandinsertthatelementintothesortedportionin the
order specified.
5. Repeattheaboveprocessuntilalltheelementsfromtheunsortedportionaremovedintothe sorted
portion.
6. Stopthe program.

Program:
publicclassInsertionSort{
publicstaticvoidinsertionSort(intarray[]){ int
n=[Link];
for(intj=1;j<n;j++){
int key=array[j];int
i=j-1;
while((i>-1)&&(array[i]>key)){
array[i+1]=array[i];
i--;
}
array[i+1]=key;
}
}
publicstaticvoidmain(Stringa[]){
int[]arr1={9,14,3,2,43,11,58,22};
[Link]("BeforeInsertionSort");
for(int i:arr1){
[Link](i+"");
}
[Link],println();
insertionSort(arr1);//sortingarrayusinginsertionsort
[Link]("After Insertion Sort");
for(inti:arr1){

7
[Link](i+"");
}
}
}
Output:

BeforeInsertionSort 9
14 3 2 43 11 58 22
After InsertionSort
2 3911 14 224358

Result:
Thustheprogramforsolvingproblemsinarrayusinginsertionsortalgorithmhas been
executedandtheoutputwasverified.

8
6
1

Common questions

Powered by AI

Selection sort's primary strength is its simplicity and performance consistency, with a time complexity of O(n^2) regardless of the initial order of elements. However, it performs more swaps than necessary, decreasing efficiency in practice. Insertion sort, on the other hand, is more efficient for nearly sorted data due to minimal shifting, with average-case efficiency improvements reflected in less time complexity compared to fully unsorted lists. Its weakness lies in its poorer performance on large, unsorted arrays due to a worse-case time complexity of O(n^2).

In the binary search algorithm, the middle element of the list is determined by calculating the index as the sum of the starting index and half the size of the current list segment being considered. This middle element is crucial because it serves as the pivot in deciding whether to continue the search in the left subarray if the key is smaller or in the right subarray if the key is larger, thus effectively halving the search area each time .

The main purpose of the loop inside the insertion sort algorithm is to insert elements from the unsorted portion of the array into their correct position within the sorted portion. This is achieved by repeatedly comparing and shifting elements in the sorted portion to the right until the appropriate position for the unsorted element is found. Once the position is determined, the element is inserted into the sorted section, thereby expanding it .

Binary search is considered more efficient because it reduces the problem size by half with each comparison, leading to a time complexity of O(log n), compared to O(n) for sequential search. This improved performance is delivered when operating on sorted arrays, as the method fundamentally relies on eliminating half of the search space at each step, something sequential search cannot exploit .

Sequential search compares all elements systematically by examining each element one by one from the beginning to the end of the array. If it finds an element equal to the target, the search ends successfully. If it reads through all elements without finding a match, it concludes that the target is not present in the array. This method does not require the array to be sorted .

The fundamental difference between sequential search and binary search is how they traverse the array. Sequential search inspects each element in the array one by one until it finds the target or reaches the end of the array. It can operate on unsorted arrays. In contrast, binary search requires the array to be sorted. It operates by repeatedly dividing the sorted array into halves, comparing the target with the middle element, and eliminating one-half of the array from further consideration each time a comparison is made .

The selection sort algorithm finds the smallest element by comparing the first element with all other elements in the list, keeping track of the minimum value found. Once it identifies the smallest element, it swaps this element with the first element of the list. It then repeats this process for the next position in the list until the entire array is sorted .

The swap operation in selection sort involves exchanging the positions of two elements in the array. After each pass through the array, selection sort identifies the smallest unsorted element and swaps it with the first unsorted element. This operation is essential because it progressively builds a sorted array from left to right, ensuring that the smallest unsorted elements are placed correctly, thus resulting in a sorted list by the end of all passes .

Insertion sort is more efficient for partially sorted arrays because it involves shifting elements to make space for inserting unsorted elements into the sorted part of the array. In a partially sorted array, fewer elements require shifting, which minimizes the number of operations required. Therefore, insertion sort approaches linear time complexity in such cases, making it faster compared to its average/quadratic time complexity when dealing with completely unsorted arrays .

The condition of the array being sorted is crucial for the efficient operation of the binary search algorithm. Binary search leverages the sorted order to eliminate half of the search space during each step of the algorithm, allowing it to achieve logarithmic time complexity. Without a sorted array, binary search cannot determine which half of the array to disregard, rendering it ineffective and unable to perform as efficiently .

You might also like