In: Computer Science
in java we need to order a list , if we create a program in java what are the possible ways of telling your program how to move the numbers in the list to make it sorted, where each way provides the required result.
list the name of sorting with short explanation
Having any doubts please comment below.Thank you.
Here i providing Bubble Sort:
Bubble sort is working based on the repeatedly swapping the adjacent elements if they are in wrong order.
For better understanding please take a look at java program.
JAVA CODE:
import java.util.*;
public class Sort {
public static void main(String args[]){
Scanner sc = new
Scanner(System.in);
System.out.println("Enter the size
of list:");//prompting user to enter size of list
int n = sc.nextInt(); // reading
size from user
List<Integer> l = new
ArrayList(); // creating array list of integers
System.out.println("Enter array
elements :"); // prompting user to enter elements
//loop for reading elements from
user
for(int i=0 ; i<n ; i++)
{
l.add(sc.nextInt()); // reading element from user and add it to the
list
}
//Implementing Bubble Sort
for (int i = 0; i < n-1;
i++)
{
for(int j=0 ;
j<n-i-1 ; j++)
{
if(l.get(j) > l.get(j+1)) // condition for
checking next number is greater
{
// swapping numbers
int temp = l.get(j);
l.set(j, l.get(j+1));
l.set(j+1, temp);
}
}
}
System.out.println("\nSorted list
\n"+l); // printing sorted list
}
}