java
public class BubbleSort {
public static void main(String[] args) {
int[] array = {64, 34, 25, 12, 22, 11, 90};
System.out.println("Original array:");
printArray(array);
bubbleSort(array);
System.out.println("Sorted array:");
printArray(array);
}
static void bubbleSort(int[] array) {
int n = array.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (array[j] > array[j+1]) {
// swap array[j+1] and array[j]
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
static void printArray(int[] array) {
int n = array.length;
for (int i = 0; i < n; ++i)
System.out.print(array[i] + " ");
System.out.println();
}
}
这个程序首先定义了一个未排序的整数数组,然后通过 bubbleSort 方法进行排序。这个方法通过嵌套循环比较每对相邻的元素,如果它们的顺序错误就交换它们。经过这个过程,最大的元素会被“冒泡”到数组的末尾。这个过程重复进行,直到整个数组被排序。printArray 方法则用于打印数组中的元素。
联系客服