在Java中,对数值进行排序可以通过多种排序算法实现,以下是几种常用的排序方法:
快速排序
```java
import java.util.Arrays;
public class FastSortDemo {
public static void main(String[] args) {
int[] arr = {6, 1, 2, 7, 9, 3};
fastSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
public static void fastSort(int[] arr, int low, int high) {
if (low < high) {
int pivotIndex = partition(arr, low, high);
fastSort(arr, low, pivotIndex - 1);
fastSort(arr, pivotIndex + 1, high);
}
}
public static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}
}
冒泡排序
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {6, 1, 2, 7, 9, 3};
bubbleSort(arr);
for (int num : arr) {
System.out.print(num + " ");
}
}
public static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
选择排序
```java
public class SelectionSort {
public static void main(String[] args) {
int[] arr = {6, 1, 2, 7, 9, 3};
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 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
public class InsertionSort {
public static void main(String[] args) {
int[] arr = {6, 1, 2, 7, 9, 3};
insertionSort(arr);
for (int num : arr) {
System.out.print(num + " ");
}
}
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集合框架