算法解析可看https://blog.csdn.net/weixin_44035017/article/details/95811991
冒泡排序
package com.code;
import java.util.Arrays;
//psvm
//sout
public class BubbleSort {
public static void main(String[] args)
{
int arr[]=new int[]{23,42,12,8,9,10};
BubbleSort sorter=new BubbleSort();
sorter.bunbblesort(arr);
}
public void bunbblesort(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;
}
}
}
show(arr);
}
public void show(int arr[]){
for(int i:arr){
System.out.print(i+" ");
}
System.out.println();
}
}
直接选择排序
package com.code;
import java.util.Arrays;
//psvm
//sout
public class SelectSort {
public static void main(String[] args)
{
int arr[]=new int[]{23,42,12,8,9,10};
SelectSort selectSort=new SelectSort();
selectSort.sort(arr);
}
public void sort(int arr[]){
int index;
for(int i=0;i<arr.length-1;i++){
index=i;
for(int j=i+1;j<arr.length;j++){
if(arr[j]<arr[index]) {
index = j;
}
}
if(index!=i){
int temp=arr[index];
arr[index]=arr[i];
arr[i]=temp;
}
}
show(arr);
}
public void show(int arr[]){
for(int i:arr){
System.out.printf(i+" ");
}
System.out.println();
}
}
插入排序
package com.code;
import java.util.Arrays;
//psvm
//sout
public class Insertion_Sort {
public static void main(String[] args)
{
int arr[]=new int[]{23,42,12,8,9,10};
Insertion_Sort sort=new Insertion_Sort();
sort.Insertion_Sort(arr,arr.length);
}
public void Insertion_Sort(int array[], int length) {
int i, j;
int Tmp;
for (i = 1; i < length; i++) {
Tmp = array[i];
for (j = i; j > 0 && array[j - 1] > Tmp; j--)
array[j] = array[j - 1]; //后移元素
array[j] = Tmp; //插入
}
show(array);
}
public void show(int arr[]){
for(int i:arr){
System.out.printf(i+" ");
}
System.out.println();
}
}