本文最后更新于230 天前,其中的信息可能已经过时,如有错误请发送邮件到qiqin-chang@qq.com
冒泡排序:
说明:以此比较相邻元素,并将较大元素移至后方
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 < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] arr = {5, 4, 3, 2, 1};
bubbleSort(arr);
for (int num : arr) {
System.out.print(num + " ");
}
}
}
选择排序:
说明:每次选择一个最小元素与未排序元素首部进行替换
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 = {3, 2, 5, 4, 1};
selectionSort(arr);
for (int num : arr) {
System.out.print(num + " ");
}
}
}
插入排序:
说明:每次将未排序的首元素插入已排序的队列中
public class InsertionSort {
public static int[] insertionSort(int[] a){
if(a.length<=1) return a;
for(int i = 1; i<a.length; ++i){
int value = a[i];
int j = i-1;
//查找插入的位置
while(j>=0&&value<a[j]){
a[j+1] = a[j];
j--;
}
a[j+1] = value;
}
return a;
}
public static void main(String[] args) {
int[] a = {10, 9, 7, 4, 3, 2, 1, 8};
System.out.println("之前的排序:");
System.out.println(Arrays.toString(a));
insertionSort(a);
System.out.println("之后的排序:");
System.out.println(Arrays.toString(a));
}
}
希尔排序:
import java.util.Arrays;
public class Main {
public static int[] shellSort(int[] a){
//不断缩小增量
for(int x=a.length/2;x>0;x=x/2){
//增量为1的插入排序
for(int i=x; i<a.length; i++){
int value = a[i];
int j = i-x;
//查找插入的位置
while(j>=0&&value<a[j]){
a[j+x] = a[j];
j-=x;
}
a[j+x] = value;
}
}
return a;
}
public static void main(String[] args) {
int[] a = {10, 9, 7, 4, 3, 2, 1, 8};
System.out.println("之前的排序:");
System.out.println(Arrays.toString(a));
shellSort(a);
System.out.println("之后的排序:");
System.out.println(Arrays.toString(a));
}
}
计数排序:
说明:使用位置+偏移量的方式,用数组确定位置用出现次数表示偏移量,逆序确定每个数字的位置
//计数排序
public class Main {
public static void main(String[] args) {
int[] a = {8, 10, 12, 9, 8, 12, 8}; //输入的数组
int[] r = new int[a.length]; //输出的数组
int min = Integer.MAX_VALUE; //数组中的最小值
int max = Integer.MIN_VALUE; //数组中的最大值
for (int i = 0; i < a.length; i++) {
min = Math.min(min, a[i]);
max = Math.max(max, a[i]);
}
int[] s = new int[max - min + 1]; //计数数组 统计每个数字出现的次数
for (int i = 0; i < a.length; i++) {
s[a[i]-min]++;
}
int[] s1 = new int[max - min + 1]; //排序数组 表示数字应在排序后数组的位置 当前值=前一位的值+计数数组的值
s1[0]=s[0];
for (int i = 1; i < s.length; i++) {
s1[i]=s1[i-1]+s[i];
}
//逆序填写数字到相应位置
for (int i = a.length-1; i >=0; i--) {
r[s1[a[i]-min]-1]=a[i];
s1[a[i]-min]--;
}
//输出数组
for(int j=0;j<r.length;j++){
System.out.print(r[j]+" ");
}
}
}