Sorting and searching are the basic operations we can perform on arrays. Sorting means rearranging the elements of a given list or array in ascending or descending order, while searching means finding an element or its index in a list.
Although there are various algorithms available to perform these operations, in this article, we will use some of them to sort and search elements in java. We will study them one by one.
Method 1: Use the built-in method of the array
In this section, we will discuss the following methods that help in sorting and searching elements in an array.
sort() - It is a static method of Arrays class that sorts the array passed as parameter in ascending order.
grammar
Arrays.sort(nameOfarray);
binarySearch() - It is also a static method of Arrays class. It accepts two parameters, the first is the array whose elements need to be searched, and the second is the element we need to find in that array.
It returns the index number of the element passed as argument.
grammar
Arrays.binarySearch(nameOfarray, element);
Example
import java.util.*; public class Srch { public static void main(String args[]) { int araylist[] = {9, 3, 56, 0, -2, -6, 2, 1, 80}; System.out.print("The given unsorted list: "); // for each loop that prints the original array for (int print : araylist) { System.out.print(print + " "); } Arrays.sort(araylist); // method to sort given array System.out.println(); System.out.print("The newly sorted list: "); // for each loop that prints the newly sorted array for (int print : araylist) { System.out.print(print + " "); } System.out.println(); // method to search given element int position = Arrays.binarySearch(araylist, 1); if(position > -1) { System.out.print("Element is available at index: " + position); } else { System.out.print("Element is not available"); } } }
Output
The given unsorted list: 9 3 56 0 -2 -6 2 1 80 The newly sorted list: -6 -2 0 1 2 3 9 56 80 Element is available at index: 3
Method 2: Use our custom logic
Sort using bubble sort
algorithm
Step 1 - First, declare and initialize an array named "araylist" and an integer variable named "temp" to temporarily store the shifted elements.
Step 2 - Use two for loops to compare the i-th position element with the i-1th element. Create an if block inside the second for loop to check which element is larger and then we perform a shift operation to rearrange the elements in ascending order.
Step 3 - Now using each loop, we will print the sorted array.
Example
public class Bubble { public static void main(String[] args) { int araylist[] = {9, 3, 56, 0, 2, 1, 80}; int temp = 0; System.out.print("The given unsorted list: "); for (int print : araylist) { System.out.print(print + " "); } for (int i = 0; i < araylist.length; i++) { for (int j = i+1; j < araylist.length; j++) { if(araylist[i] > araylist[j]) { temp = araylist[i]; araylist[i] = araylist[j]; araylist[j] = temp; } } } System.out.println(); System.out.print("The newly sorted list: "); for (int print : araylist) { System.out.print(print + " "); } } }
Output
The given unsorted list: 9 3 56 0 2 1 80 The newly sorted list: 0 1 2 3 9 56 80
Search using linear search
algorithm
Step 1 - First, declare and initialize an array named "araylist" and an integer variable named "searchElem" which we will search for in the array . We also need two integer variables "isFound" and "locate".
Step 2 - Now, create a for loop that will run up to the length of the array. In this loop, use an if block to check if "searchElem" exists in the array. If available, its index is stored in the variable "locate" and the variable "isFound" is incremented to 1.
Step 3 - Next, we create an if else block to check if the variable "isFound" increases to 1. If it equals 1, it means the element was found and we return the index. If not, the statement in the else block will be executed.
Example
public class Linear { public static void main(String[] args) { int araylist[] = {9, 3, 56, 0, 2, 1, 80}; int searchElem = 0; int isFound = 0; int locate = 0; for(int i = 0; i < araylist.length; i++) { if(searchElem == araylist[i]) { isFound = 1; locate = i; } } if(isFound == 1) { System.out.print("Element is available at index: " + locate); } else { System.out.print("Element is not available"); } } }
Output
Element is available at index: 3
in conclusion
In this article, we discussed how to sort array elements and perform search operations to find specific elements of that array. We can use the built-in method called "sort()" or any sorting and searching algorithm.
The above is the detailed content of Sort and search elements in Java. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools