共計 762 個字符,預(yù)計需要花費(fèi) 2 分鐘才能閱讀完成。
有很多種排序算法可以在 Java 中實現(xiàn),以下是一些常見的排序算法的示例代碼:
- 冒泡排序(Bubble Sort)
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 arr[j + 1]) {// 交換 arr[j] 和 arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
- 插入排序(Insertion Sort)
public class InsertionSort {public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i = 0 && arr[j] > key) {arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
}
- 選擇排序(Selection Sort)
public class SelectionSort {public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {if (arr[j] < arr[minIndex]) {minIndex = j;}
}
// 交換 arr[i] 和 arr[minIndex]
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
這些只是排序算法中的幾個示例,還有很多其他的排序算法,如快速排序、歸并排序等。你可以根據(jù)具體的需求選擇合適的排序算法。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完