选择排序 java代码
时间: 2023-10-13 21:12:45 浏览: 31
好的,以下是选择排序的Java代码:
```
public static void selectionSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
```
希望这个代码可以帮到你!现在,您还有其他问题吗?
相关问题
选择排序java代码
以下是Java选择排序的示例代码:
```java
package com.lfsun.main.point.demostructure.sort;
import java.util.Arrays;
public class SelectionSort {
public static void selectionSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
System.out.println(Arrays.toString(arr));
}
public static void main(String[] args) {
selectionSort(new int[] {0, 4, 9, 88, -5});
}
}
```
Java选择排序(Selection Sort)是一种简单直观的排序算法,它的思想是每次从待排序的元素中选择最小(或最大)的元素,将其放到已排序的元素末尾。通过不断选择最小的元素,直到所有元素排序完成。[2]
以上代码中,`selectionSort`方法接收一个整型数组作为参数,通过两重循环实现选择排序。外层循环遍历数组,内层循环遍历剩余部分,找到最小元素并交换位置,重复执行直到排序完成。时间复杂度为O(n^2),不适用于大规模数据排序。[3]
选择排序代码java
以下是选择排序的Java代码示例:
```java
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;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
selectionSort(arr);
System.out.println("Sorted array:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
```