pTutorial

New way to learn Programming

Java Array Sorting In Ascending Order

Following Java program sort the array in an ascending order without using any pre-define Java class method. We use for loop with conditional statement if-else to sort the array.

Java array soring example

import java.util.Scanner;
public class ArraySorting {
    static int n;
    public static void input1(int[] b){
        Scanner uk=new Scanner(System.in);
        System.out.println("Enter " + n + "subject marks");
	    for(int l=0;l<b.length;l++){
                b[l]= uk.nextInt();
	     }
    }
	
    public static void sorting(int[] p){
	int i,j;
	int temp;
	for(i=0;il<n;i++){
       for(j=0;j<n-i-1;j++){
           if (p[j]  > p[j+1]){
                temp = p[j];
                p[j]=p[j+1];
				p[j+1]=temp;
           }
		}
	}
}
    public static void display(int[] b){
        System.out.println("Sorted Marks:");
	for(int l=0;l<b.length;l++){
	System.out.println(b[l]);
	}
    }
    
    public static void main(String[] args) {
        Scanner uk=new Scanner(System.in);
	System.out.println("Enter the number of element");
	n=uk.nextInt();
	int x[]=new int[n];	
	input1(x);
	sorting(x);
	display(x);
    }
}





Output

Enter the number of element
3
Enter 3 subject marks
38 7 120
Sorted Marks:
7
38
120

See Also


QUOTES OF THE DAY

Wonder is the first cause of philosophy.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER