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

Sort char Array Example

08:02 PASSOVE INCOME 0 Comments


                  Sort char Array Example

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

0 comments: