-
Notifications
You must be signed in to change notification settings - Fork 0
/
BubbleSort.java
50 lines (42 loc) · 1.17 KB
/
BubbleSort.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package DSAalgorithm;
import java.util.*;
class Sort
{
public void bubble_sort(int arr[])
{
for(int i=0;i<arr.length-1;i++)
{
// for(int j=0;j<arr.length-1;j++) // there is unnecessary comparison //
for(int j=0;j<arr.length-1-i;j++)// remove the unnecessary comparison //
{
if(arr[j]>arr[j+1])
{
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
}
public class BubbleSort
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of array:");
int size=sc.nextInt();
int arr[]=new int[size];
System.out.println("Enter the elements of array:");
for(int i=0;i<arr.length;i++)
{
arr[i]=sc.nextInt();
}
Sort s1=new Sort();
s1.bubble_sort(arr);
System.out.println("Sorted Array is:");
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
}