java Bubble Sort
时间: 2024-05-03 21:23:25 浏览: 9
Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller or larger elements "bubble" to the top of the list.
Here is the Java code for Bubble Sort:
```
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 7, 3, 1};
bubbleSort(arr);
for(int i=0; i<arr.length; i++){
System.out.print(arr[i] + " ");
}
}
public static void bubbleSort(int[] arr){
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
}
```
In this code, we have an array of integers that we want to sort using Bubble Sort. We define a method called `bubbleSort` that takes an array as input and sorts it using the Bubble Sort algorithm.
The outer loop iterates through the array from the first element to the last element. The inner loop iterates through the array from the second element to the last element.
Inside the inner loop, we compare the current element with the previous element. If the current element is smaller than the previous element, we swap them.
After the inner loop completes, the largest element is at the end of the array. We repeat this process until the entire array is sorted.
Finally, we print the sorted array using a for loop.