Skip to Content

Java Sort float Array Example

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