forked from javakurssi/Tuntimateriaalit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.java
More file actions
57 lines (47 loc) · 1.83 KB
/
Copy pathBubbleSort.java
File metadata and controls
57 lines (47 loc) · 1.83 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
package lesson7;
/**
* This example demonstrates the implementation of the famous Bubble sort algorithm.
* (https://en.wikipedia.org/wiki/Bubble_sort)
*
* Other, higher performing sorting algorithms are e.g. Merge sort and Quick sort
*/
public class BubbleSort {
// Bubble sort sorts the provided integer array into ascending order
public static void bubbleSort(int[] arr) {
int arrayLength = arr.length;
// The outer loop takes care of going through each index in the array
for (int i = 0; i < arrayLength - 1; i++) {
// The inner loop compares subsequent array value and switch their order
// if they are in incorrect order (larger value is before the smaller value)
for (int j = 0; j < arrayLength - i - 1; j++) {
// Are the subsequent array values in wrong order?
if (arr[j] > arr[j + 1]) {
// Switch `j` and `j+1`!
// In that case, switch the values between `j` and `j+1`
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
// Print the current result
printArray(arr);
}
}
// Helper method for printing an array
private static void printArray(int[] arr) {
for (int value : arr) {
System.out.print(value + " ");
}
System.out.println();
}
// Example usage of the bubble sort
public static void main(String[] args) {
int[] arrayToSort = {64, 25, 90, 12, 22, 11};
System.out.println("Original array:");
printArray(arrayToSort);
// Perform the bubble sort
bubbleSort(arrayToSort);
System.out.println("Sorted array:");
printArray(arrayToSort);
}
}