-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathBubble.java
More file actions
54 lines (47 loc) · 1.68 KB
/
Bubble.java
File metadata and controls
54 lines (47 loc) · 1.68 KB
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
/* Bubble Sort implementation in Java */
public class Bubble
{
//Simple Bubble Sort implementation
//Following function will sort the array in Increasing (ascending) order
void sort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
// Last i elements are already in place, so the inner loops will run until it reaches the last i elements
for (int j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1]) //To Sort in decreasing order, change the comparison operator to '<'
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
//Following is a slightly modified bubble sort implementation, which tracks the list with a flag to check if it is already sorted
void modified_sort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
boolean flag = false; //Taking a flag variable
// Last i elements are already in place, so the inner loops will run until it reaches the last i elements
for (int j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1]) //To Sort in decreasing order, change the comparison operator to '<'
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
flag = true; //Setting the flag, if swapping occurs
}
}
if(!flag) //If not swapped, that means the list has already sorted
{
break;
}
}
}
}