How to Sort a Float Array in Java


In this example, let us see how to sort a float array by sorting method of Arrays class in Java.util package.

Source Code

package com.beginner.examples;

import java.util.Arrays;

public class SortFloatArray {

	public static void main(String[] args) {
		
	    //create float array.
	    float[] f1 = new float[]{3f,2f,5f,4f,1f};
	    
	    System.out.print("Original Array : ");
	    for(int index=0; index < f1.length ; index++) {
	    	System.out.print("  "  + f1[index]);
	    }
	     
	    /*
	     *  To sort java float array use Arrays.sort() method of java.util package.
	     */
	    Arrays.sort(f1);
	    System.out.println();
	    System.out.print("Sorted float array : ");
	    for(int index=0; index < f1.length ; index++) {
	    	System.out.print("  "  + f1[index]);
	    }
	      
	}

}

Output:

Original Array :   3.0  2.0  5.0  4.0  1.0
Sorted float array :   1.0  2.0  3.0  4.0  5.0

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments