Computer Science, asked by chineng52331, 9 months ago

Write a java program to sort 'N' elements of an array

Answers

Answered by prashantrohilla32
1

Answer:

import java.util.Scanner;  

public class Main

{

public static void main(String[]args)

{

    Scanner sc=new Scanner(System.in);

 int n;

  System.out.print("Enter array length:");

    n=sc.nextInt();

 int []a=new int [n];

  System.out.print("Enter array elements:");

 for(int i=0;i<n;i++)

 {

     a[i]=sc.nextInt();

 }

    int temp;

    int flag=0;

    {

     System.out.print("Unsorted array :");

     

        for(int i=0;i<a.length;i++)

         {

         System.out.print(a[i]+" , ");

         

         }

    }

   

    System.out.println();

  for(int i=0;i<a.length;i++){

   for(int j=0;j<a.length-i-1;j++)

    {if(a[j]<a[j+1])

    {

     temp=a[j];

     a[j]=a[j+1];

     a[j+1]=temp;

     flag=flag+1;

    }

   }

   if(flag==0)

   {break;}

  }

  System.out.print("Sorted array :");

  for(int i=0;i<a.length;i++){

   System.out.print(a[i]+" , ");

  }

   

   

}}

Explanation:

Attachments:
Answered by Oreki
1

import java.util.Arrays;

import java.util.Scanner;

public class SortUptoN {

   public static void main(String[ ] args) {

       Scanner sc = new Scanner(System.in);

       System.out.print("Enter array length - ");

       int[ ] array = new int[sc.nextInt( )];

       System.out.println("Enter array elements - ");

       for (int i = 0; i < array.length; i++)

           array[i] = sc.nextInt( );

       System.out.print("Enter the position up to be sorted - ");

       Arrays.sort(array, 0, sc.nextInt( ) - 1);

       System.out.println(Arrays.toString(array));

   }

}

Similar questions