public class Dem {
public static void main(String[] args) {
int[] arr = {6,5,4,3,2,1};
prinArray(arr); //排序前
bubbleSort(arr); // 冒泡排序
prinArray(arr); //排序后
System.out.println("----------------"); //换行
prinArray(arr); //排序前
selectSort(arr); //选择排序
prinArray(arr); //排序后
}
//冒泡排序
public static void 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;
}
}
}
}
//选择排序
public static void selectSort(int[] arr){
for (int i = 0; i < arr.length; 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;
}
}
}
}
//遍历数组
public static void prinArray(int[] arr){
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
}
}
|
|