Java
Java copied to clipboard
BubbleSort.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);
// Measure the time taken by bubbleSort
long startTime = System.currentTimeMillis();
bubbleSort(array);
long endTime = System.currentTimeMillis();
System.out.println("\nSorted array:");
printArray(array);
System.out.println("Time taken by Bubble Sort: " + (endTime - startTime) + " milliseconds");
}
// Function to perform Bubble Sort
static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
// Function to print an array
static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
public class BubbleSort {
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; 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[] array = {5, 4, 3, 2, 1};
System.out.println("排序前的数组:");
for (int num : array) {
System.out.print(num + " ");
}
bubbleSort(array);
System.out.println("\n排序后的数组:");
for (int num : array) {
System.out.print(num + " ");
}
}
}