Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathBubbleSort.java
More file actions
Latest commit
77 lines (55 loc) · 1.63 KB
/
Copy pathBubbleSort.java
File metadata and controls
77 lines (55 loc) · 1.63 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
69
70
71
72
73
74
75
76
77
importjava.util.Arrays;
importjava.util.Scanner;
classBubbleSort {
/**
* Method to sort the array
*
* @param arr Reference to the array
*/
publicvoidsort(int[] arr) {
intlength = arr.length; // Length of the array
for (inti = 0; i < length; i++) {
booleanhasSwapped = false;
for (intj = 0; j < length - 1 - i; j++) {
inta = arr[j];
intb = arr[j + 1];
if (a > b) {
swap(arr, j, j + 1);
hasSwapped = true; // Denoting that the code has swapped 2 numbers
}
}
if (!hasSwapped) // If there was no swapping, that means the array is sorted and there is no need to continue the loop.
break;
}
}
/**
* Swaps the two numbers in the array
*
* @param arr Reference to the array
* @param i Index of the first number to swap
* @param j Index of the second number to swap
*/
privatevoidswap(int[] arr, inti, intj) {
inttemp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
classMain {
publicstaticvoidmain(String[] args) {
intsize;
Scannerscanner = newScanner(System.in);
System.out.print("Enter the size of the array: ");
size = scanner.nextInt();
int[] arr = newint[size];
for (inti = 0; i < size; i++) {
System.out.print("Enter element #" + (i + 1) + ": ");
arr[i] = scanner.nextInt();
}
scanner.close();
System.out.println("Unsorted Array: " + Arrays.toString(arr)); // Representing the unsorted array
BubbleSortbs = newBubbleSort(); // Creating the object of the BubbleSort class
bs.sort(arr); // Calling the sort method
System.out.println("Sorted Array: " + Arrays.toString(arr)); // Representing the sorted array
}
}