首页 > 代码库 > Java冒泡排序
Java冒泡排序
一、从小到大:
代码:
public class DemoThree {
static double[] sort(double[] nums){
double temp=0;//临时变量
//开始排序
for (int i = 0; i < nums.length-1; i++) {
for (int j = 0; j < nums.length-i-1; j++) {
if(nums[j]>nums[j+1]){
temp=nums[j+1];
nums[j+1]=nums[j];
nums[j]=temp;
}
}
}
return nums;
}
public static void main(String[] args) {
double[] n={1,5,4.5,6.5,1.5,3.0};
System.out.println("排序前");
for (double d : n) {
System.out.print(d+"\t");
}
System.out.println("\n---------------------");
n=sort(n);//调用方法进行排序
System.out.println("排序后");
for (double d : n) {
System.out.print(d+"\t");
}
}
}
结果如图:
二、从大到小
代码:
public class DemoThree {
static double[] sort(double[] nums){
double temp=0;//临时变量
//开始排序
for (int i = 0; i < nums.length-1; i++) {
for (int j = 0; j < nums.length-i-1; j++) {
if(nums[j]<nums[j+1]){
temp=nums[j+1];
nums[j+1]=nums[j];
nums[j]=temp;
}
}
}
return nums;
}
public static void main(String[] args) {
double[] n={1,5,4.5,6.5,1.5,3.0};
System.out.println("排序前");
for (double d : n) {
System.out.print(d+"\t");
}
System.out.println("\n---------------------");
n=sort(n);//调用方法进行排序
System.out.println("排序后");
for (double d : n) {
System.out.print(d+"\t");
}
}
}
结果如图:
Java冒泡排序