在Java中,对int数组进行排序可以使用多种排序算法,其中一些常见的方法包括:
选择排序
public class SelectionSort {public static void main(String[] args) {int[] arr = {1, 3, 2, 45, 65, 33, 12};selectionSort(arr);for (int num : arr) {System.out.print(num + " ");}}public static void selectionSort(int[] arr) {for (int i = 0; i < arr.length - 1; i++) {int k = i;for (int j = k + 1; j < arr.length; j++) {if (arr[j] < arr[k]) {k = j;}}if (i != k) {int temp = arr[i];arr[i] = arr[k];arr[k] = temp;}}}}
冒泡排序
public class BubbleSort {public static void main(String[] args) {int[] arr = {9, 7, 8, 2, 5, 1, 3, 6, 4};bubbleSort(arr);for (int item : arr) {System.out.print(item + " ");}}public static void bubbleSort(int[] arr) {for (int i = 0; i < arr.length - 1; i++) {for (int j = 0; j < arr.length - i - 1; j++) {if (arr[j] > arr[j + 1]) {int temp = arr[j];arr[j] = arr[j + 1];arr[j + 1] = temp;}}}}}
插入排序
public class InsertionSort {public static void main(String[] args) {int[] arr = {5, 2, 0, 4, 1, 3};insertionSort(arr);for (int item : arr) {System.out.print(item + " ");}}public static void insertionSort(int[] arr) {for (int i = 1; i < arr.length; i++) {int key = arr[i];int j = i - 1;while (j >= 0 && arr[j] > key) {arr[j + 1] = arr[j];j = j - 1;}arr[j + 1] = key;}}}
使用Java内置的`Arrays.sort()`方法
import java.util.Arrays;public class BuiltInSort {public static void main(String[] args) {int[] arr = {9, 7, 8, 2, 5, 1, 3, 6, 4};Arrays.sort(arr);for (int item : arr) {System.out.print(item + " ");}}}
以上代码示例展示了如何使用不同的排序算法对int数组进行排序。你可以选择最适合你需求的方法。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/122155.html