请帮助尝试对数组进行排序
public class selectionsorter
{
public selectionsorter(int[] x)
{
theArray=x;
}
public void sort()
{
for(int i=0; i<theArray.length-1;i++)
{
start=i;
findMinPos();
}
}
public void findMinPos()
{
int minpos=start;
for(int i=0;i<theArray.length;i++)
{
if(i>start)
{
if(theArray[i]<theArray[start])
{
start=i;
}
}
}
swap();
}
public void swap()
{
temp=theArray[start];
theArray[start]=theArray[minpos];
theArray[minpos]=temp;
}
private int[] theArray;
private int minpos;
private int start;
private int temp;
}
测试文件
public class selectionsortertester
{
public static void main(String[] args)
{
int[] x ={3,7,5,6,9,2};
selectionsorter y=new selectionsorter(x);
y.sort();
for(int i=0; i<x.length;i++)
System.out.print(x[i]+" ");
}
}
我希望它排序的数组它从最低到最高,它做的第一个数字,输出是“2 7 5 6 9 3”请帮助和感谢 有人知道它为什么会这样做吗?我如何修复它,谢谢
# 1 楼答案
问题是,在方法中,所有变量都保持为Class attributes,而不是局部变量,并且所有方法都在更改类变量
这是不正确的
把这些从课堂上移除
现在将这些值作为方法参数传递:
参考this SO question了解有关类属性的更多信息
# 2 楼答案
你可以这样做
见文件here