In Java sorting and searching an element in an array is very easy. Unlike C, where we have to make all the functions to work, Java has inbuilt functions to do the same work. To sort an array there is a sort function and to search an element in a sorted array there is a binarySearch() function. To learn more about these functions please follow the articles mentioned below:
Sorting: Arrays.sort() in Java with Examples
Time Complexity: O (n log n)
Syntax for Sorting:
Searching: Arrays.binarySearch() in Java with Examples
For using Binary search array must be sorted previously
- If the input array is not sorted, the results are undefined and negative.
- If there are duplicates, there is no guarantee which one will be found.
Time Complexity: O (log n)
Syntax for Binary Searching:
We could always create user-defined functions but the inbuilt functions in Java are already using the least complexity algorithms so there is no need to make such functions.
Example 1: Finding an element in a sorted array.
Element 2 found at index: 1
Example 2: Sorting an array and searching for an element in the sorted array.
Sorted Array: 1 2 3 4 5 6 7 8 9 10 Element 2 found at index: 1
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Java Program for Anagram Substring Search (Or Search for all permutations)
- Serial Sort v/s Parallel Sort in Java
- Java Program for Odd-Even Sort / Brick Sort
- java.util.stream.IntStream/LongStream | Search an element
- Java Program to Search an Element in a Linked List
- Java Program to Search an Element in a Circular Linked List
- Sort an Array and Insert an Element Inside Array in Java
- Quick Sort vs Merge Sort
- Java Program for Binary Search (Recursive and Iterative)
- Arrays.binarySearch() in Java with examples | Set 2 (Search in subarray)
- Java Program for Linear Search
- Stack search() Method in Java
- Binary Search in Java
- Search equal, bigger or smaller in a sorted array in Java
- Search a string in Matrix Using Split function in Java
- Java Program to Search for a File in a Directory
- Binary Search on Java Vector
- Sort an array of pairs using Java Pair and Comparator
- Maximum element in an array such that its previous and next element product is maximum
- Collections.sort() in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.