/*
需求:给一个数组进行排序:{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]
public static void bubbleSort(int[] a){
for(int x = 0;x<a.length-1;x++){
for(int y=x+1;y<a.length;y++){
if(a[y]<a[x]){//虽然只是把交换的代码放到这里,结果就出来了。
int temp;
temp = a[x] ;
a[x] = a[y] ;
a[y] = temp ;
}
//swap(y,y+1);交换的时候,实质没有将数组传过去 你可以使用应该swap(int[]a,x,y) 把数组也传过去, x , y是需要交换位置的下标
}
}
}
swap(y,y+1);
这行代码并没有对数组进行操作,应该传入角标和数组才能完成
private static void swap(int a,int b)
{
int temp = a;
a = b;
b = temp;
}
这个方法出问题了,