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

Java Programs: Binary Search & Sorting

Uploaded by

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

Java Programs: Binary Search & Sorting

Uploaded by

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

2-BTECH-CSE:: I SEM

OOPS THROUGH JAVA PROGRAMMING LAB


EXPERIMENT: 2
2(A) Aim: Write a java program to search for an element in a given list of
elements using binary search mechanism
Binary Search in Java
Binary search is one of the searching techniques applied when the input is sorted here
we are focusing on finding the middle element that acts as a reference frame whether
to go left or right to it as the elements are already sorted. This searching helps in
optimizing the search technique with every iteration is referred to as binary search and
readers do stress over it as it is indirectly applied in solving questions.

Binary Search Algorithm in Java


Below is the Algorithm designed for Binary Search:
1. Start
2. Take input array and Target
3. Initialise start = 0 and end = (array size -1)
4. Intialise mid variable
5. mid = (start+end)/2
6. if array[ mid ] == target then return mid
7. if array[ mid ] < target then start = mid+1
8. if array[ mid ] > target then end = mid-1
9. if start<=end then goto step 5
10. return -1 as Not element found
11. Exit
PROGRAM:

// Binary Search in Java

import [Link];
class BinarySearchExample
{
int binarySearch(int array[], int element, int low, int high)
{
// Repeat until the pointers low and high meet each other
while (low <= high)
{
// get index of mid element
int mid = low + (high - low) / 2;

// if element to be searched is the mid element


if (array[mid] == element)
return mid;

// if element is less than mid element


// search only the left side of mid
if (array[mid] < element)
low = mid + 1;

// if element is greater than mid element


// search only the right side of mid
else
high = mid - 1;
}
return -1;
}
public static void main(String args[]) {
// create an object of Main class
BinarySearchExample bs = new BinarySearchExample ();
// create a sorted array
int[] array = { 3, 4, 5, 6, 7, 8, 9 };
int n = [Link];
// get input from user for element to be searched
Scanner input = new Scanner([Link]);
[Link]("Enter element to be searched:");
// element to be searched
int element = [Link]();
[Link]();
// call the binary search method
// pass arguments: array, element, index of first and last element
int result = [Link](array, element, 0, n - 1);
if (result == -1)
[Link]("Not found");
else
[Link]("Element found at index " + result);
}
}

OUTPUT:
Enter element to be searched:
6
Element found at index 3
2(B):AIM: java program to sort for an element in a given list of elements using
bubble sort

Bubble Sort is the simplest sorting algorithm that works by repeatedly


swapping the adjacent elements if they are in the wrong order. Bubble Sort in
Java is not the best method to sort an array but is one of the most basic
implementations for one to learn.

Algorithm for Bubble Sort in Java


The following is the algorithm to sort array in increasing order using bubble
sort in Java:
1. Start
2. Initiate two values n as size of array ,also i and j to traverse array.
3. Put i=0 and j=1.
4. While traversing if array[i] > array[j] swap both the numbers.
5. Increment the value i and j then goto Step 3.
6. If the value of i > n-1 and j > n and n>1 then
 n=n-1
 goto Step 2
7. Exit

Program;

import [Link];

public class CodesCracker


{
public static void main(String[] args)
{
int n=10, i, j, x;
int[] array = new int[n];
Scanner s = new Scanner([Link]);

[Link]("Enter 10 Elements in Random Order: ");


for(i=0; i<n; i++)
{
array[i] = [Link]();
}
for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(array[j]>array[j+1])
{
x = array[j];
array[j] = array[j+1];
array[j+1] = x;
}
}
}

[Link]("\nThe new sorted array is:");


for(i=0; i<n; i++)
[Link](array[i]+ " ");
}
}

Output:
Enter 10 elements in random order;
4
7
3
10
8
5
9
3
7
6
The new Sorted order is: 3 3 4 5 6 7 7 8 9 10
2(c): aim: Write a java program using stringbuffer to delete remove character

The delete(int start, int end) method of Java StringBuffer class is used to delete the
substring from specified start index to exclusive end index of this sequence. If the start
and end index were same then no deletion take place and this sequence remains
unchanged.

Syntax:: public StringBuffer delete(int start, int end)


Program:
import [Link];

public class StringBufferDeleteExample


{
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer("");

[Link]("enter your string value: ");


Scanner sc = new Scanner([Link]);
[Link]([Link]());

[Link]("enter start index: ");


int start = [Link]();
[Link]("enter end index: ");
int end = [Link]();
// printing the substring after deleting
[Link]("count: "+[Link](start,end));
[Link]();
}
}

Output:
enter your string value: string buffer
enter start index: 3
enter end index: 7
count: strbuffer

Common questions

Powered by AI

Bubble sort is considered suboptimal for large datasets due to its inefficient time complexity of O(n^2) in the average and worst-case scenarios. It requires several passes through the list, making many comparisons and swaps, which are not practical compared to more efficient algorithms like quicksort or merge sort with time complexities of O(n log n).

In the bubble sort algorithm, elements are swapped if they are in the wrong order relative to each other. The process involves repeatedly comparing each pair of adjacent elements and swapping them if the first is greater than the second. This comparison and potential swap are done iteratively, moving through the list, until the entire list is sorted .

The `delete(int start, int end)` method of the StringBuffer class is used to delete a sequence of characters within a string between the specified start index, inclusive, and end index, exclusive. If the start and end indices are the same, no deletion occurs and the string remains unchanged. This method helps manipulate the string content by removing certain parts .

The primary condition for effectively applying a binary search algorithm on a list is that the list must be sorted. This condition is crucial because the algorithm relies on comparing the middle element to the target and determining whether to search in the left or right half of the list based on this comparison .

The condition `start <= end` is significant in the binary search algorithm as it ensures that the search continues only when there's a valid segment of the array left to examine. This check prevents the algorithm from running indefinitely in cases where the element is not present, as it bounds the search space. Omitting it could lead to infinite loops if the element is not found .

Bubble sort is a suitable educational tool because it is simple to understand and implement. Its basic operations of repeated comparisons and swaps make it a straightforward example to illustrate sorting logic without the complexity of more efficient algorithms. It clarifies the fundamental mechanics of sorting and offers insight into algorithmic thinking .

In the binary search algorithm, the `mid` variable plays a crucial role by determining the middle element of the current search interval. The middle element is used as a pivot point to compare with the target value. Depending on the outcome of this comparison, the search space is halved, and the algorithm continues either on the left or right subarray .

If the input list is not sorted, using the binary search method can lead to incorrect results or failure to find the target element altogether. Since binary search assumes a sorted input to effectively halve the search space in comparison to the target, an unsorted list disrupts this logical split, hence the search algorithm would not function correctly .

Using the `delete(int start, int end)` method would be ineffective if the start and end indices are incorrectly specified; this could lead to unintended modifications or exceptions if indices go beyond the bounds of the string. If start equals end, no characters would be removed, rendering the method ineffective in changing the string .

In bubble sort, the iteration mechanism involves multiple passes through the array, where in each pass the largest unsorted element is moved to its correct position. By repeatedly bubbling up the next largest unsorted element to the top, eventually all elements are sorted after several iterations, each completing with fewer elements left to sort .

You might also like