用冒泡排序,对三个数字按照由小到大进行排序。以23、11、17为例,代码如下:
import java.util.Scanner;
public class woo {
static int[] bubbleSort(int[] date) {
boolean isSwap;
for(int j = 1; j < date.length; j++) {
isSwap = false;
for(int i = 0; i < date.length - j; i++) {
if(date[i] > date[i+1]) {
date[i] = date[i] ^ date[i+1];
date[i+1] = date[i] ^ date[i+1];
date[i] = date[i] ^ date[i+1];
isSwap = true;
}
}
if(isSwap == false)
break;
}
return date;
}
public static void main(String args[]) {
int date[] = new int[3];
System.out.println("输入三个整数:");
Scanner num = new Scanner(System.in);
for(int i = 0;i < date.length; i++)
date[i] = num.nextInt();
date = bubbleSort(date);
for(int count = 0; count < date.length; count++)
System.out.print(date[count] +"\t");
System.out.println("");
}
}
扩展资料:
通常排序算法,可以分为两大类。
非线性时间比较类排序:通过比较来决定元素间的相对次序,由于其时间复杂度不能突破O(nlogn),因此称为非线性时间比较类排序。包括交换排序、插入排序、选择排序、归并排序。
线性时间非比较类排序:不通过比较来决定元素间的相对次序,它可以突破基于比较排序的时间下界,以线性时间运行,因此称为线性时间非比较类排序。包括计数排序、桶排序、计数排序。
参考资料:冒泡法排序——百度百科
package work;
import java.util.Scanner;//导包,获取键盘输入
/**
* 键盘输入A、B、C三个值,按从大到小顺序输出。
**/
public class Demo01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入数字a");
int a = sc.nextInt();
System.out.println("输入数字b");
int b = sc.nextInt();
System.out.println("输入数字c");
int c = sc.nextInt();
import java.util.*;
public class Exercise06
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //利用键盘输入功能
System.out.print("a=");
int a = input.nextInt() ; //输入数字a 只能为int类型
System.out.print("b=");
int b = input.nextInt() ;
System.out.print("c=");
int c = input.nextInt() ;
Exercise06 e = new Exercise06() ;
e.sort(a,b,c);
}
void sort(int a,int b,int c)
{
int temp = 0 ;
if(a>b){
temp = a;
a = b ;
b = temp ;
}
if(a>c){
temp = a;
a = c ;
c = temp ;
}
if(b>c){
temp = b;
b = c ;
c = temp ;
}
System.out.println(a+","+b+","+c);
}
}
不过我还是建议你多用一楼的方法
class Test4
{
public static void main(String[] args)
{
int[] arr={1,4,2};//定义数组。
Sort s=new Sort();
s.sort(arr);
s.print(arr);
}
}
class Sort//定义方法排序数组。
{
void sort(int[] a)
{
for (int i=0;i
for (int j=i+1;j
if (a[i]>a[j])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
//定义方法打印。
void print(int[] a)
{
System.out.print("[");
for (int i=0;i
if (i
System.out.print(a[i]+",");
}else
System.out.print(a[i]+"]");
}
}
}
//该方法比较灵点,希望对你有助。