/*
需求:给一个数组进行排序:{5,6,9,2,1,4,8,7,3}
*/
public class ArrayDemo1
{
public static void main(String[] args)
{
int[] arr ={5,6,9,2,1,4,8,7,3};
printArray(arr);
//selectSort(arr);
bubbleSort(arr);
printArray(arr);
}
public static void selectSort(int[] a)
{
for(int x = 0;x
{
for(int y =x+1;y
{
if(a[x]>a[y])
swap(a[x],a[y]);
}
}
}
private static void swap(int a,int b)
{
int temp = a;
a = b;
b = temp;
}
public static void bubbleSort(int[] a)
{
for(int x = 0;x<a.length-1;x++)
{
for(int y=0;y<a.length-x-1;y++)
{
if(a[y]>a[y+1])
swap(y,y+1);
}
}
}
public static void printArray(int[] a)
{
System.out.print("[");
for(int x=0;x<a.length;x++)
{
if(x!=a.length-1)
{
System.out.print(a[x]+",");
}
else
System.out.println(a[x]+"]");
}
}
}
——————————————————————
打印结果是:
[5,6,9,2,1,4,8,7,3]
[5,6,9,2,1,4,8,7,3]