How to sort an array and search an element inside it using Java



Problem Description

How to sort an array and search an element inside it?

Solution

Following example shows how to use sort () and binarySearch () method to accomplish the task. The user defined method printArray () is used to display the output:

import java.util.Arrays;

public class MainClass {
   public static void main(String args[]) throws Exception {
      int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
      Arrays.sort(array);
      printArray("Sorted array", array);
      int index = Arrays.binarySearch(array, 2);
      System.out.println("Found 2 @ " + index);
   }
   private static void printArray(String message, int array[]) {
      System.out.println(message + ": [length: " + array.length + "]");
      
      for (int i = 0; i < array.length; i++) {
         if(i != 0) {
            System.out.print(", ");
         }
         System.out.print(array[i]);                     
      }
      System.out.println();
   }
}

Result

The above code sample will produce the following result.

Sorted array: [length: 10]
-9, -7, -3, -2, 0, 2, 4, 5, 6, 8
Found 2 @ 5

Linear Search

Following example shows search array element with Linear Search.

public class HelloWorld {
   public static void main(String[] args) {
      int[] a = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
      int target = 0;
      
      for (int i = 0; i < a.length; i++) {
         if (a[i] == target) {
            System.out.println("Element found at index " + i);
            break;
         } 
      } 
   }
}

Result

The above code sample will produce the following result.

Element found at index 6 

Bubble Sort

Following example shows sort array element with Bubble Sort.

public class HelloWorld {
   static void bubbleSort(int[] arr) {
      int n = arr.length;
      int temp = 0;
      for(int i = 0; i < n; i++) {
         for(int j=1; j < (n-i); j++) {
            if(arr[j-1] > arr[j]) { 
               temp = arr[j-1]; 
               arr[j-1] = arr[j];
               arr[j] = temp;
            } 
         } 
      } 
   }  
   public static void main(String[] args) {
      int arr[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 }; 
      System.out.println("Array Before Bubble Sort");
      
      for(int i = 0; i < arr.length; i++) {
         System.out.print(arr[i] + " ");
      } 
      System.out.println();
      bubbleSort(arr);
      System.out.println("Array After Bubble Sort");
      
      for(int i = 0; i < arr.length; i++) {
         System.out.print(arr[i] + " ");
      } 
   }  
}  

Result

The above code sample will produce the following result.

Array Before Bubble Sort
2 5 -2 6 -3 8 0 -7 -9 4 
Array After Bubble Sort
-9 -7 -3 -2 0 2 4 5 6 8      
java_arrays.htm
Advertisements