基本排序算法:冒泡排序、选择排序 、快速排序
import java.util.Random;
public class Demo01 {
public static void main(String[] args) {
int[] numbers=new int[6];
System.out.println("\n冒泡排序");
intiArray(numbers);
printArray(numbers);
//冒泡排序
boolean flag=false;
for(int i=0;i<numbers.length;++i){
System.out.print("\n第"+(i+1)+"轮");
flag=true;
for(int j=0;j<numbers.length-1-i;++j){
if(numbers[j]>numbers[j+1]){
int temp=numbers[j];
numbers[j]=numbers[j+1];
numbers[j+1]=temp;
flag=false;
}
System.out.print("第"+(i+1)+"轮第"+(j+1)+"次交换:");
printArray(numbers);
}
//没有交换退出
if(flag)break;
}
System.out.println("\n选择排序");
intiArray(numbers);
printArray(numbers);
//选择排序
int minIndex;
for(int i=0;i<numbers.length-1;++i){
minIndex=i;
for(int j=i+1;j<numbers.length;++j){
//找小的
if(numbers[minIndex]>numbers[j]){
minIndex=j;
}
}
if(minIndex!=i){
int temp=numbers[i];
numbers[i]=numbers[minIndex];
numbers[minIndex]=temp;
}
System.out.print("\n第"+(i+1)+"轮交换:");
printArray(numbers);
}
}
//打印数组
public static void printArray(int ... numbers){
for(int num:numbers){
System.out.print(num+" ");
}
}
//初始化数组
public static void intiArray(int[] numbers){
Random rd=new Random();
//初始化
for(int i=0;i<numbers.length;++i){
numbers[i]=rd.nextInt(100);
}
}
}