☞Sorting is process of arranging data in some logical order.
☞This logical order may be ascending or descending in case of numeric values or dictionary order in case of alphanumeric values.
☞We can perform following sorting operations on an array.
1. Bubble Sort 2. Selection Sort
☞Logic starts with comparison of first two elements and if the left element is greater than right element, they swap their position. Comparison proceeds till the end of the array.
import java.util.*; class BubbleSort{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); System.out.println("Enter the size"); int size=sc.nextInt(); int arr[]=new int[size]; int i,temp; /*inputting elements in an array*/ System.out.println("Enter the elements"); for(i=0;i<arr.length;i++) arr[i]=sc.nextInt(); /*logic of bubble sort*/ for(int round=1;round<=arr.length-1;round++){ /*check the element with the next element according to rounds*/ for(i=0;i<=arr.length-1-round;i++){ if(arr[i]>arr[i+1]){ /*swap the current element with the next element*/ temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } } } /*Printing in ascending order*/ System.out.println("The numbers in ascending order are: "); for(i=0;i<arr.length;i++) System.out.print(arr[i]+" "); } }
Enter the size 5 Enter the elements 74 47 84 34 63 The numbers in ascending order are 34 47 63 74 84