Array-promo

Question

Bubble sort an unsorted array.

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;
public class BubbleSortArray 
{ 
    public static void main(String args[]) 
	{ 
	    int[] arr;
	    Scanner sc=new Scanner(System.in);
	    System.out.println("Enter  no. of elements in the array");
	    int n = sc.nextInt(); 
	    
	    System.out.println("Enter numbers in array");
	    arr=new int[n];
	    for(int i=0;i< n;i++)
	    {
	    arr[i]=sc.nextInt();
	    }
	    
	    System.out.println("Unsorted Array:"); 
	    for (int i=0; i< n; ++i) 
	    {
		    System.out.print(arr[i] + " "); 
		    System.out.println(); 
	    }
	    
	    /*Sorting of array*/
	    for (int i = 0; i < n-1; i++)
	    {
	        for (int j = 0; j < n-i-1; j++)
	        {
	            if (arr[j] > arr[j+1]) 
	            { 
	                // swap arr[j+1] and arr[i] 
	                int temp = arr[j]; 
	                arr[j] = arr[j+1]; 
	                arr[j+1] = temp; 
		    	} 
		    }
		}
		
		System.out.println("Sorted Array:"); 		
		for (int i=0; i< n; ++i) 
		{
		    System.out.print(arr[i] + " "); 
		    System.out.println(); 
		} 	
		
	}
} 
				
			

Coding Store

10-minute Stress-Buster Games

Leave a Reply

Your email address will not be published. Required fields are marked *