forked from hariom20singh/cargame1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.java
More file actions
61 lines (56 loc) · 1.67 KB
/
BubbleSort.java
File metadata and controls
61 lines (56 loc) · 1.67 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
import java.util.*;
//Problem : Bubble Sort
public class BubbleSort {
public static void bubbleSort(int arr[]) {
for(int turn=0; turn<arr.length-1; turn++) {
for(int j=0; j<arr.length-1-turn; j++) {
if(arr[j] > arr[j+1]) {
//swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
public static void modifiedBubbleSort(int arr[]) {
for(int turn=0; turn<arr.length-1; turn++) {
boolean swapped = false;
for(int j=0; j<arr.length-1-turn; j++) {
if(arr[j] > arr[j+1]) {
//swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
swapped = true;
}
}
if(swapped == false) {
break;
}
}
}
public static void bubbleSortDescending(int arr[]) {
for(int turn=0; turn<arr.length-1; turn++) {
for(int j=0; j<arr.length-1-turn; j++) {
if(arr[j] < arr[j+1]) {
//swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
public static void printArr(int arr[]) {
for(int i=0; i<arr.length; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static void main(String args[]) {
int arr[] = {5, 4, 3, 2, 1};
bubbleSortDescending(arr);
printArr(arr);
}
}