Table of Contents
Method 1: Use the built-in method of the array
grammar
Example
Output
Method 2: Use our custom logic
Sort using bubble sort
algorithm
in conclusion
Home Java javaTutorial Sort and search elements in Java

Sort and search elements in Java

Aug 30, 2023 pm 08:09 PM
java sorting java search Element sorting

Sort and search elements in Java

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);
Copy after login

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);
Copy after login

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");
      }
   }
} 
Copy after login

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
Copy after login

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 + " ");
      }     
   }     
}
Copy after login

Output

The given unsorted list: 9 3 56 0 2 1 80 
The newly sorted list: 0 1 2 3 9 56 80 
Copy after login

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");
      }
   }
}
Copy after login

Output

Element is available at index: 3
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

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...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

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

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

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...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

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 elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles