用java把十个数用冒泡排序法排序
- 首先我们介绍一下,什么是冒泡排序
在冒泡排序的过程中,不断地比较数组中相邻的两个元素,较小者向上浮,较大者往下沉,整个过程和水中气泡上升的原理相似。
那我们思考一下如何来编写这个程序:
- 我们需要输入10个数
- 我们需要对10个数进行两两比较
- 我们需要输出数组排序前后的一个比较
我们有了思路,就开始编写代码吧!
import java.util.Scanner;
class ex1{
public static void main(String[] args){
Scanner sr=new Scanner(System.in);
//写到这里,是不是需要定义10个数组呢?不然怎么存放是不是?
int[] x=new int[10];
//然后我们进行一个提醒
System.out.println("-------在下方输入10个数,该程序将使用冒泡排序进行排序------");
//之后我们需要利用一个循环进行赋值
for(int i=0 ;i<10 ;i++){
x[i]=sr.nextInt();
}
}
}
**
到这里我们的第一步就完成了,接下来进行第二步,对数组里的数组进行两两比较。
**
public static void bubbleSort(int[] x){
for(int i = 0 ; i<x.length-1 ; i++ ){
for(int j = 0 ; j<x.length-i-1 ; j++ ){
if(x[j]>x[j+1]){
int temp=x[j];
x[j]=x[j+1];
x[j+1]=temp;}
}
System.out.print("第"+i+"轮排序的结果是:");
}
}
**
最后一步,讲比较后的数组进行一个输出比较
**
public static void printSc(int[] x){
for(int i = 0 ; i < 10 ; i++ ){
System.out.print(x[i]+ " ");
}
}
- 这样的话整个程序就算编写完成了,将bubbleSort,和printSc进行调用整理一下便是以下代码
import java.util.Scanner;
class ex1 {
public static void main(String[] args) {
Scanner sr = new Scanner(System.in);
//写到这里,是不是需要定义10个数组呢?不然怎么存放是不是?
int[] x = new int[10];
//然后我们进行一个提醒
System.out.println("-------在下方输入10个数,该程序将使用冒泡排序进行排序------");
//之后我们需要利用一个循环进行赋值
for (int i = 0; i < 10; i++) {
x[i] = sr.nextInt();
}
System.out.print("冒泡排序比较前:");
printSc(x);
bubbleSort(x);
System.out.print("冒泡排序比较后:");
printSc(x);
}
public static void bubbleSort(int[] x) {
for (int i = 0; i < x.length - 1; i++) {
for (int j = 0; j < x.length - i - 1; j++) {
if (x[j] > x[j + 1]) {
int temp = x[j];
x[j] = x[j + 1];
x[j + 1] = temp;
}
}
System.out.print("第" + (i + 1) + "轮排序的结果是:");
printSc(x);
System.out.print("\n");
}
}
public static void printSc(int[] x) {
for (int i = 0; i < 10; i++) {
System.out.print(x[i] + " ");
}
}
}
- 让我们看一下运行结果吧!
非常的完美,如果有什么不明白的可以评论留言都会解答的哦!
扫描二维码关注公众号,回复:
13308637 查看本文章