-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.java
More file actions
48 lines (45 loc) · 984 Bytes
/
BubbleSort.java
File metadata and controls
48 lines (45 loc) · 984 Bytes
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
import java.io.*;
class BubbleSort
{
void bubbleSort(int arr[])
{
boolean flag = true;
while(flag == true)
{
flag = false;
for(int i=0;i<arr.length-1;i++)
{
if(arr[i] > arr[i+1])
{
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
flag = true;
}
}
if(flag == false)
break;
}
}
void printArray(int arr[])
{
System.out.println("Sorted array: ");
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]+" ");
}
public static void main(String args[]) throws IOException
{
BubbleSort bs = new BubbleSort();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("How many elements: ");
int n = Integer.parseInt(br.readLine());
int arr[] = new int[n];
for(int i=0;i<arr.length;i++)
{
System.out.print("Enter element: ");
arr[i] = Integer.parseInt(br.readLine());
}
bs.bubbleSort(arr);
bs.printArray(arr);
}
}