编写一个Java程序,编写以下方法,按升序排列三个数并输出public static void sort(int num1,int num2,int num3)
时间: 2024-10-20 19:15:11 浏览: 27
在Java中,你可以通过创建一个临时变量交换最大的两个数,然后将剩余的那个数与较小的数比较并交换,以此类推,直到所有的数都被排序。这里是一个简单的冒泡排序算法实现这个`sort`方法:
```java
public class Main {
public static void main(String[] args) {
int num1 = 5;
int num2 = 8;
int num3 = 3;
sort(num1, num2, num3);
System.out.println("Sorted numbers: " + num1 + ", " + num2 + ", " + num3);
}
public static void sort(int a, int b, int c) {
// Bubble sort algorithm
for (int i = 0; i < 3; i++) {
if (a > b) {
// Swap a and b
int temp = a;
a = b;
b = temp;
}
if (b > c) {
// Swap b and c
temp = b;
b = c;
c = temp;
}
// If a is still the largest, it means no swap happened in this iteration
// so we don't need to check again
if (a != b || b != c) {
if (a > b) {
temp = a;
a = b;
b = temp;
}
}
}
// After sorting, the method will have modified the input arguments directly
// No need to return anything
}
}
```
当你运行这段程序,它会按升序排列输入的三个数,并打印出来。
阅读全文