Home > Java > javaTutorial > Java Example - Array Sorting and Searching

Java Example - Array Sorting and Searching

黄舟
Release: 2017-02-18 10:15:34
Original
1575 people have browsed it

The following example demonstrates how to use the sort () and binarySearch () methods to sort an array and find elements in the array. We define the printArray() output result:

/*
 author by w3cschool.cc
 文件名:Main.java
 */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();
	}}
Copy after login

The output result of running the above code is:

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

The above is the Java example - array sorting and search content. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


Related labels:
source:php.cn
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