Java冒泡排序参考代码
package algorithm;
import java.util.Arrays;
public class BubbleSort2 {
public static void main(String[] args) {
int[]arr1= {-2,4,5,0,-5,-9};
int len1=arr1.length;
int temp=0;
for(int j=0;j<len1-1-0;j++) {
if(arr1[j]>arr1[j+1]) {
temp=arr1[j];
arr1[j]=arr1[j+1];
arr1[j+1]=temp;
}
}
System.out.println("第一趟后数组:"+Arrays.toString(arr1));
for(int j=0;j<len1-1-1;j++) {
if(arr1[j]>arr1[j+1]) {
temp=arr1[j];
arr1[j]=arr1[j+1];
arr1[j+1]=temp;
}
}
System.out.println("第二趟后数组:"+Arrays.toString(arr1));
for(int j=0;j<len1-1-2;j++) {
if(arr1[j]>arr1[j+1]) {
temp=arr1[j];
arr1[j]=arr1[j+1];
arr1[j+1]=temp;
}
}
System.out.println("第三趟后数组:"+Arrays.toString(arr1));
for(int j=0;j<len1-1-3;j++) {
if(arr1[j]>arr1[j+1]) {
temp=arr1[j];
arr1[j]=arr1[j+1];
arr1[j+1]=temp;
}
}
System.out.println("第四趟后数组:"+Arrays.toString(arr1));
for(int j=0;j<len1-1-4;j++) {
if(arr1[j]>arr1[j+1]) {
temp=arr1[j];
arr1[j]=arr1[j+1];
arr1[j+1]=temp;
}
}
System.out.println("第五趟后数组:"+Arrays.toString(arr1));
}
}
package algorithm;
import java.util.Arrays;
public class BubbleSort3 {
public static void main(String[] args) {
int[]arr1= {1,4,7,0,-9,-7};
int len1=arr1.length;
for(int i=0;i<len1-1;i++) {
for(int j=0;j<len1-1-i;j++) {
if(arr1[j]>arr1[j+1]) {
int temp=arr1[j];
arr1[j]=arr1[j+1];
arr1[j+1]=temp;
}
}
System.out.println("第"+(i+1)+"趟排序结果"+Arrays.toString(arr1));
}
}
}
package algorithm;
import java.util.Arrays;
public class BubbleSort4 {
public static void main(String[] args) {
int[]arr1={1,2,3,4,5,6,78} ;
int len1=arr1.length;
boolean flag=false;
for(int i=0;i<len1-1;i++) {
for(int j=0;j<len1-1-i;j++) {
if(arr1[j]>arr1[j+1]) {
int temp=arr1[j];
arr1[j]=arr1[j+1];
arr1[j+1]=temp;
flag=true;
}
}
System.out.println("第"+(i+1)+"趟排序结果"+Arrays.toString(arr1));
if(!flag) {
break;
}else {
flag=false;
}
}
}
}