-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOptimizedBubbleSort.java
64 lines (54 loc) · 1.54 KB
/
OptimizedBubbleSort.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
57
58
59
60
61
62
63
64
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package name;
import java.util.Arrays;
/**
*
* @author HP
*/
public class OptimizedBubbleSort {
Integer[] a;
public OptimizedBubbleSort(Integer[] array){
this.a = array;
}
public void bubbleSort(Integer[] a){
for(int i = 0; i < a.length; i++){
boolean flag = false;
for(int j = 0; j < a.length - (i+1); j++){
if (a[j] > a[j+1]){
swap(j,j+1);
flag = true;
}
System.out.println(
"i = "
+ (i + 1)
+ "; j = "
+ (j + 1)
+ "; "
+ Arrays.deepToString(a)
);
}
if(!flag)
break;
}
}
public void swap (int i, int j){
int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
class OptimizedBubbleSortTest{
public static void main(String []args){
Integer[] a = {5, 6, 8, 9, 21, 23, 76, 92, 107, 8143};
OptimizedBubbleSort sorter = new OptimizedBubbleSort(a);
System.out.println("Before sort: ");
System.out.println(Arrays.deepToString(a));
sorter.bubbleSort(a);
System.out.println("After sort: ");
System.out.println(Arrays.deepToString(a));
}
}