您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,有多种方法可以对数组进行排序
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {34, 12, 56, 78, 90};
Arrays.sort(arr);
System.out.println("Sorted array: " + Arrays.toString(arr));
}
}
public class Main {
public static void main(String[] args) {
int[] arr = {34, 12, 56, 78, 90};
bubbleSort(arr);
System.out.println("Sorted array: " + Arrays.toString(arr));
}
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; 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;
}
}
}
}
}
public class Main {
public static void main(String[] args) {
int[] arr = {34, 12, 56, 78, 90};
selectionSort(arr);
System.out.println("Sorted array: " + Arrays.toString(arr));
}
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;
}
}
// Swap arr[i] and arr[minIndex]
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
public class Main {
public static void main(String[] args) {
int[] arr = {34, 12, 56, 78, 90};
insertionSort(arr);
System.out.println("Sorted array: " + Arrays.toString(arr));
}
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
}
以上示例展示了如何使用Java对整数数组进行排序。你可以根据需要修改这些示例以适应不同类型的数组和排序要求。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。