Home > Java > javaTutorial > body text

Sort and search elements in Java

WBOY
Release: 2023-08-30 20:09:10
forward
1206 people have browsed it

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!

source:tutorialspoint.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!