-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathBubbleSort.java
57 lines (48 loc) · 1010 Bytes
/
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
51
52
53
54
55
56
57
/*
Copyright (C) Deepali Srivastava - All Rights Reserved
This code is part of DSA course available on CourseGalaxy.com
*/
import java.util.Scanner;
public class BubbleSort
{
private BubbleSort(){} //this class is not for instantiation
public static void sort(int[] a, int n)
{
int x,j,temp,swaps;
for(x=n-2; x>=0; x--)
{
swaps=0;
for(j=0; j<=x; j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
swaps++;
}
}
if(swaps==0)
break;
}
}
public static void main(String[] args)
{
int i,n;
int[] a = new int[20];
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number of elements : ");
n = scan.nextInt();
for(i=0; i<n; i++)
{
System.out.print("Enter element " + (i+1) + " : ");
a[i] = scan.nextInt();
}
sort(a,n);
System.out.println("Sorted array is : ");
for(i=0; i<n; i++)
System.out.print(a[i] + " ");
System.out.println();
scan.close();
}
}