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

Java Sorting and Searching Algorithms

The document contains Java code for selection sort, bubble sort, and binary search algorithms to sort and search arrays in ascending and descending order. Selection sort and bubble sort are used to sort integer arrays and string arrays based on population data. Binary search is applied to sorted integer arrays to find a target number.

Uploaded by

Akshat
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)
25 views6 pages

Java Sorting and Searching Algorithms

The document contains Java code for selection sort, bubble sort, and binary search algorithms to sort and search arrays in ascending and descending order. Selection sort and bubble sort are used to sort integer arrays and string arrays based on population data. Binary search is applied to sorted integer arrays to find a target number.

Uploaded by

Akshat
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

/**Java program to arrange an array in ASSCENDING order using, Exchange

Selection Sort */
class ExSelSort_Asc
{
static void Arrange(int Arr[])
{
int i=0,j=0,Val=0,Pos=0,Temp=0,len=[Link];
for(i=0;i<len;i++)
{
Val=Arr[i]; //to store current element
Pos=i; //position of current element
for(j=i+1;j<len;j++)
if(Arr[j]<Val)
{
Val=Arr[j];
Pos=j;
}
Temp=Arr[i];
Arr[i]=Arr[Pos];
Arr[Pos]=Temp;
}
[Link]("Sorted Array: ");
for(i=0;i<len;i++)
[Link](Arr[i]+", ");
}
}
/**Java program to arrange an array in DESCENDING order using, Exchange
Selection Sort */
class ExSelSort_Desc
{
static void Arrange(int Arr[])
{
int i=0,j=0,Val=0,Pos=0,Temp=0,len=[Link];

for(i=0;i<len;i++)
{
Val=Arr[i]; //to store current element
Pos=i; //position of current element
for(j=i+1;j<len;j++)
if(Arr[j]>Val)
{
Val=Arr[j];
Pos=j;
}
Temp=Arr[i];
Arr[i]=Arr[Pos];
Arr[Pos]=Temp;
}
[Link]("Sorted Array: ");
for(i=0;i<len;i++)
[Link](Arr[i]+", ");
}
}
/** Java program to input name of cities and their population in 2 different arrays
and arrange all cities in Ascending order (according to their population) */
class BubbleSort_Asc
{
static void Print(String Nm[],int Arr[])
{
int i=0,j=0,len=[Link];
[Link]("\tUN-Sorted Array\nCity\t\tPopulation");
for(i=0;i<len;i++)
[Link](Nm[i]+"\t\t"+Arr[i]);

for(i=0;i<len;i++)
for(j=0;j<len-1-i;j++)
if(Arr[j]>Arr[j+1])
{
int Temp=Arr[j];
Arr[j]=Arr[j+1];
Arr[j+1]=Temp;

String str=Nm[j];
Nm[j]=Nm[j+1];
Nm[j+1]=str;
}
[Link]("\n\n\tSorted Array\nCity\t\tPopulation");
for(i=0;i<len;i++)
[Link](Nm[i]+"\t\t"+Arr[i]);
}
}
/** Java program to input name of cities and their population in 2 different arrays
and arrange all cities in Descending order (according to their population) */

class BubbleSort_Desc
{
static void Print(String Nm[],int Arr[])
{
int i=0,j=0,len=[Link];
[Link]("\tUN-Sorted Array\nCity\t\tPopulation");
for(i=0;i<len;i++)
[Link](Nm[i]+"\t\t"+Arr[i]);

for(i=0;i<len;i++)
for(j=0;j<len-1-i;j++)
if(Arr[j]<Arr[j+1])
{
int Temp=Arr[j];
Arr[j]=Arr[j+1];
Arr[j+1]=Temp;

String str=Nm[j];
Nm[j]=Nm[j+1];
Nm[j+1]=str;
}
[Link]("\n\n\tSorted Array\nCity\t\tPopulation");
for(i=0;i<len;i++)
[Link](Nm[i]+"\t\t"+Arr[i]);
}
}
/** Write a java program to input an array (in ascending order) and a number
"Num", Search inputted array for "Num", using "Binary Search Algorithm" */
class Binary_Search_Asc
{
static void Search(int Arr[], int Num)
{
int L=0, M=0, U=[Link]-1, Flag=0;
while(L<=U)
{
M=(L+U)/2;
if(Num>Arr[M])
L=M+1;
else if(Num<Arr[M])
U=M-1;
else if(Num==Arr[M])
{
Flag=1;
break;
}
}
if(Flag==1)
[Link](Num+" found at index- "+M);
else
[Link](Num+" not found");
}
}
/** Write a java program to input an array (in descending order) and a number
"Num", Search inputted array for "Num", using "Binary Search Algorithm" */
class Binary_Search_Desc
{
static void Search(int Arr[], int Num)
{
int L=0, M=0, U=[Link]-1, Flag=0;
while(L<=U)
{
M=(L+U)/2;
if(Num>Arr[M])
U=M-1;
else if(Num<Arr[M])
L=M+1;
else if(Num==Arr[M])
{
Flag=1;
break;
}
}
if(Flag==1)
[Link](Num+" found at index- "+M);
else
[Link](Num+" not found");
}
}

Common questions

Powered by AI

Implementing both ascending and descending order algorithms as illustrated allows for flexibility in data presentation and analysis. Certain contexts require data to be processed or displayed in descending order, such as ranking systems, while others may need ascending order, such as numerical organization or histogram binning. This flexibility helps cater to diverse user requirements and application needs, as well as scenarios where consistent ordering is crucial for further data processing or decision-making .

The Binary Search Algorithm, when applied to an ascending ordered array, increases the lower bound when the middle element is less than the target and decreases the upper bound when the middle is greater . In a descending ordered array, the logic is reversed; the upper bound is decreased when the middle element is greater than the target and increased when less . This inversion allows the algorithm to progress correctly through differently ordered datasets.

In the Exchange Selection Sort, the algorithm iterates through the array, selecting the smallest unsorted element and swapping it with the first unsorted element. The steps involve checking each element and finding the smallest to swap with the current index . In contrast, Bubble Sort repeatedly steps through the array, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated for each element until no more swaps are needed, indicating that the array is sorted .

The trade-off of using a linear scan for position selection in the Exchange Selection Sort algorithm involves balancing simplicity and efficiency. The linear scan guarantees that the smallest or largest element is correctly positioned, simplifying the implementation. However, this incurs an O(n^2) time complexity, making it inefficient for large datasets compared to more advanced algorithms like QuickSort or MergeSort, which have better average-case performance. Nonetheless, for small datasets, the simplicity of the linear scan can be advantageous as it involves fewer operations and setup .

Exchange Selection Sort may be preferred over Bubble Sort when the dataset is large and performance is a critical factor, because it potentially requires fewer swaps. Since it selects the smallest element and moves it directly to its final sorted position, it can be more efficient than Bubble Sort, which may require multiple swaps per pass through the dataset . This efficiency is beneficial if the cost of swapping is significantly higher than comparison operations.

The placement and scope of variables in the provided Java functions affect efficiency by minimizing memory usage and reducing reallocation if they are declared within the smallest possible scope. This can enhance readability by making it immediately clear which section of code uses the variable. Declaring variable scope broadly across the entire function, as seen in some sections of the code, may lead to unnecessary allocations and make it harder to follow which sections use a specific variable .

In real-world applications, the design of these sorting and searching algorithms makes them applicable to situations where small to medium-sized datasets need quick sorting or searching without the overhead of complex frameworks. The simplicity and straightforward implementation make them suitable for educational purposes and learning environments. However, for large datasets, these algorithms may not be efficient due to their O(n^2) time complexity for sorting and reliance on non-parallelizable code. As such, they are less applicable for high-performance needs but suitable for tasks that prioritize ease of use and implementation .

The use of static methods in the provided sorting and searching classes allows the methods to be invoked without creating an instance of the class, which simplifies usage when dealing with utility functions . The advantage is that static methods can be easily used across different classes and do not require instantiation. However, the disadvantage is limited use of polymorphism and inability to maintain state information unless global variables are used. Static methods may also overcomplicate unit testing and limit the flexibility and scalability of code architecture.

The Bubble Sort algorithm effectively pairs city names with populations by concurrently swapping both the population array and the city name array. Whenever two population elements are swapped, their corresponding city names are also swapped, ensuring that each city remains aligned with its correct population count throughout the sorting process .

The use of comments in the provided code aids debugging by clarifying the purpose of each segment, such as highlighting variable roles (e.g., current element, position of current element) and explaining key operations (e.g., element swapping). These comments make it easier for developers to trace the algorithmic flow and understand the logical reasoning behind the code, reducing the time and effort needed to identify and fix errors . However, comments are sparse, suggesting room for improvement to provide more comprehensive guidance across all sections.

You might also like