import java.util.Arrays;
public class Sort{
//冒泡排序
public static int[] bubbleSort(int[] arr){
for(int i=0;i<arr.length-1;i++){
for(int j=0;j<arr.length-i-1;j++){
if(arr[j]>arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
//选择排序
public static int[] selectSort(int[] arr){
for(int i=0;i<arr.length-1;i++){
for(int j=i+1;j<arr.length;j++){
if(arr[i]>arr[j]){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
//插入排序
public static int[] insertSort(int[] arr){
for(int i=0;i<arr.length;i++){
int temp = arr[i];
int j;
for(j=i-1;j>=0&&arr[j]>temp;j--){
arr[j+1] = arr[j];
}
arr[j+1] = temp;
}
return arr;
}
public static void main(String[] args){
int[] arr1 = {100,85,96,73,80,93,65,69,80,99};
arr1 = bubbleSort(arr1);
System.out.println(Arrays.toString(arr1));
int[] arr2 = {100,85,96,73,80,93,65,69,80,99};
arr2 = selectSort(arr2);
System.out.println(Arrays.toString(arr2));
int[] arr3 = {100,85,96,73,80,93,65,69,80,99};
arr3 = insertSort(arr3);
System.out.println(Arrays.toString(arr3));
}
}
Java中实现简单的三大排序——冒泡、选择、插入
最新推荐文章于 2024-09-02 22:33:56 发布