tianwen_j 2016-09-09 01:40 采纳率: 0%
浏览 1296

我的java数组排序后为什么和排序前是一样的顺序呢?

/*
需求:给一个数组进行排序:{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]

  • 写回答

3条回答 默认 最新

  • Mr_小艾 2016-09-09 02:05
    关注
    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是需要交换位置的下标
            }
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮