/**
*改进的冒泡排序:按照升序的方式对数组进行排序,此处我们通过添加标记位,对数组中已经有序的序列不再排序,加快了排序的速度
*@ author iamwiam
*
*/
public class Bubble {
public static void BubbleSort(int[] a){
int i,j,temp,flag;
int n = a.length;
flag = 1;//排序提前结束标志,1表示排序没有结束
for(i=1; i< n&&flag==1; i++){
for(j=0; j< n-i ; j++){
flag = 1;//若以后flag未改变,说明没有发生数组元素交换,说明可提前推出循环
if(a[j]>a[j+1]){
flag = 0;
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
public static void main(String[] args){
int[] a = {34,25,17,33,5,8,19,66};
BubbleSort(a);
for(int i =0; i< a.length;i++){
System.out.print(a[i]+" ");
}
}
/*public static void BubbleSort(int[] a){
int nElem = a.length;
int i,j;
for(i=1;i<nElem;i++){
for(j=0;j<nElem-i;j++){
if(a[j]>a[j+1])
swap(a[j],a[j+1]);
}
}
}
public static void swap(int one, int two){
int temp;
temp = one;
one = two;
two =temp;
}*/
}
改进的冒泡排序
最新推荐文章于 2020-03-15 13:54:02 发布