冒泡排序
冒泡排序算法的原理如下: [1]
比较相邻的两个元素,按照从小到大的顺序排列,若顺序错误,就把两个元素交换,直到最后一对。
import java.util.Scanner;
public class Bubbling {
public static void main(String[] args){
int num[] ;
System.out.println("请输入数n");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
num = new int[n];
System.out.println("请输入n个数");
for(int i = 0; i < n; i++){
num[i] = scanner.nextInt();
System.out.println("还差"+(n-i-1)+"个数据");
}
System.out.println("输出所有的数据");
for (int i = 0; i < n;i++) {
System.out.print(num[i]+" ");
}
System.out.println("");
for(int i = 0;i < n; i++){
for (int j = 0; j < n-1; j++) {
if(num[j]>num[j+1]){
int temp;
temp = num[j+1];
num[j+1] = num[j];
num[j] = temp;
}
}
}
for (int i = 0; i < n; i++) {
System.out.print(num[i]+" ");
}
}
}