-
Notifications
You must be signed in to change notification settings - Fork 167
Expand file tree
/
Copy pathBubbleSort.java
More file actions
68 lines (60 loc) · 1.4 KB
/
BubbleSort.java
File metadata and controls
68 lines (60 loc) · 1.4 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.Scanner;
public class BubbleSort {
static void bubbleSortAsc(int arr[], int n) {
int tmp;
boolean flag;
for (int i = 0; i < n - 1; i++) {
flag = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
flag = true;
}
}
if (!flag)
break;
}
}
static void bubbleSortDesc(int arr[], int n) {
int tmp;
boolean flag;
for (int i = 0; i < n - 1; i++) {
flag = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
flag = true;
}
}
if (!flag)
break;
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Indicate the number of elements: ");
int order;
boolean asc;
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("Type " + n + " numbers: ");
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();
System.out.println("Indicate desired order (0 for Ascending, 1 for Descending):");
order = sc.nextInt();
asc = order == 0 ? true : false;
if (asc)
bubbleSortAsc(arr, arr.length);
else
bubbleSortDesc(arr, arr.length);
System.out.println("The sorted array : ");
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println();
sc.close();
}
}