-
Notifications
You must be signed in to change notification settings - Fork 181
/
BubbleSort.java
57 lines (48 loc) · 1.48 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
51
52
53
54
55
56
import java.util.Scanner;
public class BubbleSort {
public static void main(String args[]){
Scanner scan= new Scanner(System.in);
try{
int low,high;
int n,i;
System.out.println("How many elements do you want in the array?");
n=scan.nextInt();
int a[]= new int[n];
System.out.println("Enter the array elements one by one");
for(i=0;i<n;i++)
{
a[i]=scan.nextInt();
}
System.out.println("Array before sorting is:");
printArray(a, n);
low=0;
high=n-1;
MergeSort obj = new MergeSort();
obj.sort(a, low, high);
System.out.println();
System.out.println("The sorted array is: ");
printArray(a, n);
}catch(Exception e){e.printStackTrace();}
scan.close();
}
private static void printArray(int array[], int size){
for(int i=0; i < size; i++){
System.out.println(array[i]);
}
System.out.println("\n");
}
private static void bubbleSort(int array[], int size){
for(int i=0; i < size - 1; i++){
for(int j=0; j < size - i - 1; j++){
if(array[j] > array[j+1]){
swap(array[j], array[j+1]);
}
}
}
}
private static void swap(int a, int b){
int temp = a;
a = b;
b = temp;
}
}