冒泡排序、
实现原理:
比较两个相邻位数的元素,将较大的元素交换到右端或左端,最大的元素就在最右端或是最左端;
从小-->大
1 public class MaoPao { 2 3 public static void main(String[] args) { 4 // TODO Auto-generated method stub 5 Scanner sc= new Scanner(System.in); 6 int [] num = new int [5]; 7 for (int i = 0; i < num.length; i++) { 8 System.out.println("开始输入第"+(i+1)+"个数");//输入5个整数 9 num[i]=sc.nextInt(); 10 } 11 for (int i = 0; i < num.length; i++) { 12 System.out.print(num[i]+",");//冒泡之前 13 } 14 System.out.println(" "); 15 System.out.println("开始冒泡"); 16 for (int i = 0; i < num.length-1; i++) { 17 for (int j = 0; j < num.length-1-i; j++) { 18 19 if (num[j]>num[j+1]) { 20 int temp=num[j+1]; 21 num[j+1]=num[j];//交换位置 22 num[j]=temp; 23 24 } 25 } 26 } 27 for (int i = 0; i < num.length; i++) { 28 System.out.print(num[i]+","); //冒泡之后 29 } 30 31 }
从大-->小
public class MaoPao { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc= new Scanner(System.in); int [] num = new int [5]; for (int i = 0; i < num.length; i++) { System.out.println("开始输入第"+(i+1)+"个数");//输入5个整数 num[i]=sc.nextInt(); } for (int i = 0; i < num.length; i++) { System.out.print(num[i]+",");//冒泡之前 } System.out.println(" "); System.out.println("开始冒泡"); for (int i = 0; i < num.length-1; i++) { for (int j = 0; j < num.length-1-i; j++) { if (num[j]<num[j+1]) { int temp=num[j]; num[j]=num[j+1]; num[j+1]=temp; } } } for (int i = 0; i < num.length; i++) { System.out.print(num[i]+","); //冒泡之后 } }
原文地址:https://www.cnblogs.com/fengxia/p/10061208.html
时间: 2024-10-05 05:04:55