Detailed explanation of the simplest way to write Java bubble sort
Bubble sort is a basic sorting algorithm that implements sorting by comparing and exchanging adjacent elements. , the larger (or smaller) element moves up (or down) to the correct position one at a time. This article will explain in detail the simplest way to write bubble sort in Java and provide specific code examples.
The basic idea of bubble sorting is to compare adjacent elements in sequence from left to right. If the previous element is greater than (or less than) the following element, swap their positions. After such a round of comparison and exchange, the largest (or smallest) element will "bubble" to the rightmost (or leftmost). Then perform the same operation on the remaining elements until all elements are sorted.
The following is the simplest way to write bubble sort in Java:
public class BubbleSort { public static void bubbleSort(int[] arr) { int len = arr.length; for (int i = 0; i < len - 1; i++) { for (int j = 0; j < len - 1 - i; j++) { if (arr[j] > arr[j + 1]) { // 交换相邻元素的位置 int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } public static void main(String[] args) { int[] arr = {5, 2, 8, 7, 1, 3, 9, 4, 6}; bubbleSort(arr); for (int num : arr) { System.out.print(num + " "); } } }
In the above code, we first define a bubbleSort
method, which receives an integer Array as parameter. In this method, we use two nested for loops, the outer loop controls the number of rounds, and the inner loop controls the comparison and exchange in each round.
The initial value of the inner loop is len - 1 - i
, where len
is the length of the array and i
is the current round number. This is because each round one element is moved to the correct position, so after each round there are fewer elements to compare and swap.
In the inner loop, we use arr[j]
and arr[j 1]
for comparison. If arr[j]
is greater than arr[j 1]
, their positions are swapped. Exchange uses a temporary variable temp
to temporarily store the value of arr[j]
, and then assigns the value of arr[j 1]
to arr[ j]
, and finally assign the value of temp
to arr[j 1]
to complete the exchange.
In the main
method, we create an array containing 9 integers and call the bubbleSort
method to sort the array. Finally, iterate through the array through a for loop and print out each element.
By running the above code, we can get the following output:
1 2 3 4 5 6 7 8 9
The above is the simplest way to write bubble sort in Java and specific code examples. Although bubble sort is simple, it is less efficient in practical applications, so when processing large-scale data, you should consider using a more efficient sorting algorithm.
The above is the detailed content of An in-depth analysis of the most concise bubble sort implementation in Java. For more information, please follow other related articles on the PHP Chinese website!