首页 新闻 赞助 找找看

请教大神排序错在哪?

0
[已解决问题] 解决于 2016-05-18 14:45


public class BubbleSort {
public static void main(String[] args){
int[]array={63,4,24,1,3,15};
BubbleSort sorter=new BubbleSort();
sorter.sort(array);
}
public void sort(int[] array){
for(int i=1;i<array.length;i++)
{for(int j=0;j<array.length-i;j++){
if(array[j]>array[j+1]){
int temp=array[j];
array[j]=array[j+i];
array[j+i]=temp;
}
}
}
showArray(array);
}
public void showArray(int[] array) {
for(int i:array){

System.out.print(">"+i);}
System.out.println();
}
}
求大神看看错在哪?
运行结果:>3>24>1>4>63>15
期望结果:>1>3>4>15>24>63

Sony喜乐的主页 Sony喜乐 | 菜鸟二级 | 园豆:225
提问于:2016-03-23 23:03
< >
分享
最佳答案
0

是j+1不是j+i

奖励园豆:5
jello chen | 大侠五级 |园豆:7306 | 2016-03-24 08:49

谢,自己怎么也找不出^_^

Sony喜乐 | 园豆:225 (菜鸟二级) | 2016-03-24 12:39
其他回答(1)
0
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = { 63, 4, 24, 1, 3, 15 };
            BubbleSort sorter = new BubbleSort();
            sorter.sort(array);
        }
    }
    public class BubbleSort
    {
        public void sort(int[] array)
        {
            for (int i = 0; i < array.Length; i++)
            {
                for (int j = 0; j < array.Length - i; j++)
                {
                    if (array[j] > array[j + i])
                    {
                        int temp = array[j];
                        array[j] = array[j + i];
                        array[j + i] = temp;
                        i = 0;
                    }
                }
            }
            showArray(array);
        }
        public void showArray(int[] array)
        {
            foreach (var i in array)
            {
                 Console.WriteLine(">"+i);
            }
            Console.ReadLine();
        }
    }

 

多罗贝勒 | 园豆:16 (初学一级) | 2016-03-24 09:29
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册