Skip to Content

Java Sort byte Array Example

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