Bubble Sort in Java
In bubble sort algorithm, array is checked from first element to final element. Right here, current element is compared with the subsequent element. If current element is larger than it's subsequent element,then it's swapped. in this way you can sort an array in ascending or descending order using a Bubble sort in Java.
Bubble sort in Java:
Algorithm:
Step 1: First take an array input from user and store its length in a variable like num.Step 2: For iterating through rows start a for loop and the loop structure look like :
for(int i=0;i<num;i++)
Step 3: For iterating through columns start a inner for loop and loop structure look like:
for(int j=1;j<num-i;j++)
Step 4: And check that if first element is greater that its adjacent element or any other element then swap them
Step 5: Finally you get an sorted array as your requirement ascending or descending
Java program for bubble sort :
Java program to sort elements in Descending order:
package practicepack1;
import java.util.Scanner;
public class bubblesort {
public static void
main(String[] args) {
Scanner
obj=new Scanner(System.in);
System.out.println("Enter
the number");
int
num=obj.nextInt();
int arr[]
= new int[num];
System.out.println("Enter
the elements of array you want to sort");
for(int
i=0;i<num;i++)
{
arr[i]=obj.nextInt();
}
System.out.println("Entered
array is:");
for(int
i=0;i<num;i++)
{
System.out.print(arr[i]+",");
}
for(int
i=0;i<num;i++)
{
for(int
j=1;j<num-i;j++)
{
int
temp;
if(arr[j-1]>arr[j])
{
temp=arr[j-1];
arr[j-1]=arr[j];
arr[j]=temp;
}
}
}
System.out.println("After
sorting:");
for(int
i=0;i<num;i++)
{
System.out.print(arr[i]+",");
}
}
}
Output:
Enter the number
6
Enter the elements of array you want to sort
89
56
23
45
11
23
Entered array is:
89,56,23,45,11,23,
After sorting:
11,23,23,45,56,89,
Java program to sort elements in Descending order:
package practicepack1;
import java.util.Scanner;
public class bubblesort {
public static void
main(String[] args) {
Scanner
obj=new Scanner(System.in);
System.out.println("Enter
the number");
int
num=obj.nextInt();
int arr[]
= new int[num];
System.out.println("Enter
the elements of array you want to sort");
for(int
i=0;i<num;i++)
{
arr[i]=obj.nextInt();
}
System.out.println("Entered
array is:");
for(int
i=0;i<num;i++)
{
System.out.print(arr[i]+",");
}
for(int
i=0;i<num;i++)
{
for(int
j=1;j<num-i;j++)
{
int
temp;
if(arr[j]>arr[j-1])
{
temp=arr[j-1];
arr[j-1]=arr[j];
arr[j]=temp;
}
}
}
System.out.println("After
sorting:");
for(int
i=0;i<num;i++)
{
System.out.print(arr[i]+",");
}
}
}
Output:
Enter the number
6
Enter the elements of array you want to sort
21
32
34
54
65
11
Entered array is:
21,32,34,54,65,11,
After sorting:
65,54,34,32,21,11,
Comments
Post a Comment
Please do not enter any spam link