冒泡排序大家都很熟悉了,我就简单的写写回顾一下。
一、算法描述
基本思想:每次比较两个相邻的元素,如果它们的顺序错误就把它们交换过来。
原理:每一趟只能确定将一个数归位。
步骤:如果有n 个数进行排序,只需将n-1 个数归位,也就是说要进行n-1 趟操作。而“每一趟”都需要从第1 位开始进行相邻两个数的比较,将较小的一个数放在后面,比较完毕后向后挪一位继续比较下面两个相邻数的大小,重复此步骤,直到最后一个尚未归位的数。
二、代码实现
问题描述:将n个数从小到大进行排序。
实现代码:
1 import java.util.Scanner; 2 3 public class Main { 4 public static void main(String[] args) { 5 // TODO Auto-generated method stub 6 Scanner reader = new Scanner(System.in); 7 int n = reader.nextInt(); 8 int a[] = new int[n]; 9 for(int i=0;i<n;i++) 10 a[i]=reader.nextInt(); 11 12 int tmp; 13 for(int i=0;i<n-1;i++){ 14 for(int j=0;j<n-1-i;j++){ 15 if(a[j]>a[j+1]){ 16 tmp=a[j]; 17 a[j]=a[j+1]; 18 a[j+1]=tmp; 19 } 20 } 21 } 22 23 for(int i=0;i<n;i++) 24 System.out.printf("%d ", a[i]); 25 } 26 }
问题描述:输入n个学生的姓名及其分数,将学生姓名按照分数从低到高输出。
实现代码:
1 import java.util.Scanner; 2 3 public class Main { 4 public static void main(String[] args) { 5 // TODO Auto-generated method stub 6 Scanner reader = new Scanner(System.in); 7 int n = reader.nextInt(); 8 student student[] = new student[n]; 9 for(int i=0;i<n;i++){ 10 student[i] = new student(reader.next(),reader.nextInt()); 11 } 12 13 student tmp; 14 for(int i=0;i<n-1;i++){ 15 for(int j=0;j<n-1-i;j++){ 16 if(student[j].score>student[j+1].score){ 17 tmp=student[j]; 18 student[j]=student[j+1]; 19 student[j+1]=tmp; 20 } 21 } 22 } 23 24 for(int i=0;i<n;i++) 25 System.out.printf("%s\n", student[i].name); 26 } 27 } 28 class student{ 29 public String name; 30 public int score; 31 public student(String name,int score){ 32 this.name=name; 33 this.score=score; 34 } 35 }
三、算法缺点
冒泡排序的核心部分是双重嵌套循环。冒泡排序的时间复杂度是O(N^2),时间复杂度过高。
原文:https://www.cnblogs.com/IcyYs/p/11338790.html