Sort int Array Example /*    Java Sort int Array Example    This example shows how to sort an int array...

Sort int Array Example

08:06 PASSOVE INCOME 0 Comments


                Sort int Array Example

  1. /*
  2.    Java Sort int Array Example
  3.    This example shows how to sort an int array using sort method of Arrays class of
  4.    java.util package.
  5. */
  6. import java.util.Arrays;
  7. public class SortIntArrayExample {
  8.   public static void main(String[] args) {
  9.    
  10.     //create an int array
  11.     int[] i1 = new int[]{3,2,5,4,1};
  12.    
  13.     //print original int array
  14.     System.out.print("Original Array : ");
  15.     for(int index=0; index < i1.length ; index++)
  16.       System.out.print("  "  + i1[index]);
  17.    
  18.     /*
  19.      To sort java int array use Arrays.sort() method of java.util package.
  20.      Sort method sorts int 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 an int array.
  24.     */
  25.    
  26.     //To sort full array use sort(int[] i) method.
  27.     Arrays.sort(i1);
  28.    
  29.     //print sorted int array
  30.     System.out.print("Sorted int array : ");
  31.     for(int index=0; index < i1.length ; index++)
  32.       System.out.print("  "  + i1[index]);
  33.      
  34.     /*
  35.       To sort partial int array use
  36.       sort(int[] i, int startIndex, int endIndex) method where startIndex is
  37.       inclusive and endIndex is exclusive
  38.     */
  39.    
  40.     int[] i2 = new int[]{5,2,3,1,4};
  41.     Arrays.sort(i2,1,4);
  42.    
  43.     //print sorted int array
  44.     System.out.print("Partially Sorted int array : ");
  45.     for(int index=0; index < i2.length ; index++)
  46.       System.out.print("  "  + i2[index]);
  47.   }
  48. }
  49. /*
  50. Output Would be
  51. Original Array :     3  2  5  4  1
  52. Sorted int array :     1  2  3  4  5
  53. Partially Sorted int array :     5  1  2  3  4
  54. */

0 comments: