冒泡排序

来源:互联网 发布:域名邮箱 编辑:程序博客网 时间:2024/06/04 18:06


public class Bubble_sort {


/*
* 时间复杂度为n^2
* */
/*
* 交换数组的二个元素
* */
public static void swap(int a[],int first,int second ){
int temp=a[first];
a[first]=a[second];
a[second]=temp;
}

public static void blubble_sort(int[] a){
int flag=1;
for(int i=0;i<a.length;i++){
for(int j=0;j<a.length-1-i;j++){
if(a[j]>a[j+1]){
flag=0;
swap(a,j,j+1);
}
}
if(flag==1)break;
}
}

public static  void print(int a[]){
for(int i=0;i<a.length;i++){
System.out.print(a[i]+"\t");
}
System.out.println();
}

public static void main(String[] args){
int[] a=new int[]{1,5,7,3,2};
print(a);
blubble_sort(a);
print(a);
}
}
0 0
原创粉丝点击