class Bubblesort
{
public static void main(String args[])
{
int [] arr={5,1,6,4,2,8,9};
bubble(arr);
printarray(arr);
}
public static void bubble(int[] arr)
{
for (int i=0;i<arr.length-1 ;i++ )
{
for (int y=0;y<arr.length-i-1 ; y++) //让每一次比较的元素减少,-1是为了防止数组角标越界;
{
if(arr[y]>arr[y+1]) //相邻两元素相比
{
int temp = 0;
temp = arr[y];
arr[y] = arr[y+1] ;
arr[y+1] = temp;
}
}
}
}
public static void printarray(int[] arr)
{
for (int i=0;i<arr.length ;i++ )
{
if(i!=arr.length-1)
System.out.print(arr[i]+",");
else
System.out.println(arr[i]);
}
}
} |
|