1,常规的冒泡排序,思路为:前面一个如果比后面一个大,那么就往后面排,依次类推,直到完全符合这个规律。
public class Bubbling {
public static void main(String[] args) {
//提示
Scanner sc = new Scanner(System.in);
int arr[] = new int[10];
for (int i = 0; i < 10; i++) {
System.out.println("请输入第"+(i+1)+"个数字");
arr[i] = sc.nextInt();
}
//冒泡排序过程:
for (int i = 1; i < arr.length; i++) {
for (int j = 0; j < arr.length - i; j++) {
if(arr[j]>arr[j+1]) {
int temp = arr[j];
arr[j]=arr[j+1];
arr[j+1] = temp;
}
}
}
//结果,使用for each来循环遍历数组。
for (int i : arr) {
System.out.print(i + ">");
}
}
}
2,又想了想,能否将排序过程经行封装起来,有下面代码,自己写的不太好,是个小白。
package com.report;
import java.util.Scanner;
/*
* 复杂版本的冒泡排序,面向对象方法使用冒泡排序
*/
public class SortArray {
//测试类
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//创建对象
loop loop = new loop();
//定义静态数组
int arr[]= {63,4,24,35,58,79};
System.out.println("原数组样式为:");
loop.method(arr);//调用方法
System.out.println();
System.out.println("冒泡排序后样式为:");
new loop(arr);//调用构造方法并将数组传递
loop.method(arr);//再次调用方法
}
}
//循环遍历数组类
class loop{
//无参构造
public loop() {}
//有参构造
public loop(int arr[]) {
for (int i = 1; i < arr.length; i++) {
for (int j = 0; j < arr.length - i; j++) {
if(arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
//循环遍历方法
public void method(int arr[]) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "\t");
}
}
}