Home  >  Article  >  Java  >  Java Example - Array sorting and element search

Java Example - Array sorting and element search

黄舟
黄舟Original
2017-02-18 09:55:331746browse

The following example demonstrates how to use the sort() method to sort a Java array, and how to use the binarySearch() method to find elements in the array. Here we define the printArray() method to print the array:

/*
 author by w3cschool.cc
 文件名:MainClass.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("数组排序结果为", array);
      int index = Arrays.binarySearch(array, 2);
      System.out.println("元素 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();
   }}

The output result of running the above code is:

数组排序结果为: [length: 10] -9, -7, -3, -2, 0, 2, 4, 5, 6, 8
元素 2 在第 5 个位置

The above is the Java example - array sorting and element search. For more related content, please pay attention to the PHP Chinese website (www.php. cn)!


Statement:
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