public class InsertionSort
{
public static int[] sort(int[] a,int changdu)
{
int[] temp=new int[changdu];
int i;
for(i=1;i<temp.length;i++)
{
temp[i-1]=move(a,i);

}
return temp;
}

private static int move(int[]a,int i)
{

int min=a[0];
        int smallindex=0;
int index;
for(index=i;index<a.length;index++)
{
     if(a[index]<min)
    {
  min=a[index];
      smallindex=index;
    }
}
for(int j=smallindex;j>0;j--)
 {
  a[j]=a[j-1];
 
 }
 a[i-1]=min;
     min=a[i];
 System.out.println(a[0]);

return a[i-1];
}
}输入: 1,6,4,8,3,4,7,0,9,2
显示的结果却是:0 0 0 0 0 0 0 0 0 0

解决方案 »

  1.   


    上面的那们说得没错。就是你把!!!你的循环中把最小值都给a[0]了,你再打印a[0],自然全是你输入的最小值0了
    ============================
    package Utils.Sort;public class InsertSort implements SortStrategy
    {   
           public void sort(Comparable []obj)
           { if (obj == null)
                  {  throw new NullPointerException("The argument can not be null!");
                  }
                  int size = 1;
                  while (size < obj.length)
                  {  insert(obj, size++, obj[size - 1]);
                  }        }
           private void insert(Comparable []obj, int size, Comparable c)
           { for (int i = 0 ;i < size ;i++ )
                  {  if (c.compareTo(obj[i]) < 0)
                         { System.out.println(obj[i]);
                                for (int j = size ;j > i ;j-- )
                                { obj[j] = obj[j - 1];
                                }
                               obj[i] = c;
                               break;
                         }               }        } }
      

  2.   

    但sort方法里有一个循环会自动增加i的值,不可能每次都是把0返回阿!
      

  3.   

    修改后的代码如下
    public static int[] sort(int[] a, int changdu) {
    int[] temp = new int[changdu];
    int i;
    for (i = 1; i <= temp.length; i++) {
    temp[i - 1] = move(a, i);
    }
    return temp;
    } private static int move(int[] a, int i) { int min = a[i-1];
    int smallindex = 0;
    int index;
    for (index = i; index < a.length; index++) {
    if (a[index] < min) {
    min = a[index];
    smallindex = index;
    }
    }
    for (int j = smallindex; j > 0; j--) {
    a[j] = a[j - 1]; }
    a[i - 1] = min;
    return a[i - 1];
    }
    主要问题是min的初值不正确,不应该每次给a[0],对于每次遍历其前i-1都是排好序的,只要比较其后的就可以了。还要不知道你changdu这个参数是干什么用的