Sort short Array Example /*    Java Sort short Array Example    This example shows how to sort a ...

Sort short Array Example

08:18 PASSOVE INCOME 0 Comments


                      Sort short Array Example

  1. /*
  2.    Java Sort short Array Example
  3.    This example shows how to sort a short array using sort method of Arrays class of
  4.    java.util package.
  5. */
  6. import java.util.Arrays;
  7. public class SortShortArrayExample {
  8.   public static void main(String[] args) {
  9.    
  10.     //create short array
  11.     short[] s1 = new short[]{3,2,5,4,1};
  12.    
  13.     //print original short array
  14.     System.out.print("Original Array :\t ");
  15.     for(int index=0; index < s1.length ; index++)
  16.       System.out.print("  "  + s1[index]);
  17.    
  18.     /*
  19.      To sort java short array use Arrays.sort() method of java.util package.
  20.      Sort method sorts short array in ascending order and based on quicksort
  21.      algorithm.
  22.      There are two static sort methods available in java.util.Arrays class
  23.      to sort a short array.
  24.     */
  25.    
  26.     //To sort full array use sort(short[] s) method.
  27.     Arrays.sort(s1);
  28.    
  29.     //print sorted short array
  30.     System.out.print("\nSorted short array :\t ");
  31.     for(int index=0; index < s1.length ; index++)
  32.       System.out.print("  "  + s1[index]);
  33.      
  34.     /*
  35.       To sort partial short array use
  36.       sort(short[] s, int startIndex, int endIndex) method where startIndex is
  37.       inclusive and endIndex is exclusive
  38.     */
  39.    
  40.     short[] s2 = new short[]{5,2,3,1,4};
  41.     Arrays.sort(s2,1,4);
  42.    
  43.     //print sorted short array
  44.     System.out.print("\nPartially Sorted short array :\t ");
  45.     for(int index=0; index < s2.length ; index++)
  46.       System.out.print("  "  + s2[index]);
  47.   }
  48. }
  49. /*
  50. Output Would be
  51. Original Array :     3  2  5  4  1
  52. Sorted Short array :     1  2  3  4  5
  53. Partially Sorted Short array :     5  1  2  3  4
  54. */

0 comments: