编写Java程序:获取5个数并从大到小排序
这里介绍两种方法:直接选择排序和冒泡排序
首先建一个父类Order类
import java.util.Scanner;
public class Order {
int a[] = new int[5];
int len = a.length;
public void order() {
System.out.println("请输入四个整数");
Scanner sc = new Scanner(System.in);
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
}
}
public void show() {
for (int b : a) {
System.out.print(b + " ");
}
}
}
接着建子类Order1类写直接选择排序
public class Order1 extends Order {
public void order() {
super.order();
for (int i = 0; i < len - 1; i++) {
int k = i;
for (int j = k + 1; j < len; j++) {
if (a[j] > a[k]) {
k = j;
}
}
if (k != i) {
int t = a[i];
a[i] = a[k];
a[k] = t;
}
}
}
}
再建子类Order2和Order3写两种冒泡排序
public class Order2 extends Order {
public void order() {// 冒泡排序1:小的往后冒泡
super.order();
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - 1 - i; j++) {
if (a[j + 1] > a[j]) {
int t = a[j + 1];
a[j + 1] = a[j];
a[j] = t;
}
}
}
}
}
public class Order3 extends Order {
public void order() {// 冒泡排序2:大的往前冒泡
super.order();
for (int i = 0; i < len - 1; i++) {
for (int j = len - 1; j > i; j--) {
if (a[j] > a[j - 1]) {
int t = a[j];
a[j] = a[j - 1];
a[j - 1] = t;
}
}
}
}
}
最后写测试类
public class TestOrder {
public static void main(String[] args) {
// TODO Auto-generated method stub
Order1 o1 = new Order1();// 直接选择排序
Order2 o2 = new Order2();// 冒泡排序1
Order3 o3 = new Order3();// 冒泡排序2
o1.order();
o1.show();
System.out.println();
o2.order();
o2.show();
System.out.println();
o3.order();
o3.show();
}
}