adsense


Saturday, 24 October 2015

JAVA EXAMPLES ARRAY SORT AND SEARCH PAGE 52

COMPUTER LANGUAGES HTML,C,C++.JAVA,.NET AND MULTIMEDIA basics and programs click home button



JAVA EXAMPLES ARRAY SORT AND SEARCH



Java Examples - Array sort and search

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, 16, -3, 8, 0, -7, -19, 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]
-19, -7, -3, -2, 0, 2, 4, 5,8,1 6 
Found 2 @ 5



Java Examples - Array sort and search

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, 16, -3, 8, 0, -7, -19, 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]
-19, -7, -3, -2, 0, 2, 4, 5,8,16
Found 2 @ 5


No comments: