我有一个家庭作业,按升序排列数组。显然,这是要手动完成的,而不使用任何种类的sort()
函数。按升序手动对数组进行排序
我想这样做,我需要两个for
循环:第一个循环遍历现有的数组,并创建一个临时值与数组的值和索引。第二个循环会将临时值与现有值进行比较并对它们进行排序。我一直试图编写代码,但我似乎无法做到。这里是我想出了最新的方法:
public int[] sortArray (int[] inArray)
{
//Construct the array we're using here
int[] newArray = inArray;
for(int x = 0; x < a.length; x++) //a.length = # of indices in the array
{
int tempValue = a[x];
int tempIndex = x;
for(int y = 0; y < a.length; y++)
{
if(tempValue < a[y])
{
newArray[x] = tempValue;
}
}
}
return newArray;
}
我敢肯定,这是不正确的,但如果有人可以把我在正确的方向,将不胜感激!
这可能是值得你首先看不同的排序算法的一些伪代码:http://maven.smith.edu/~thiebaut/java/sort/ – Magrangs 2012-03-29 14:45:19
你应该使用某种排序算法? – twain249 2012-03-29 14:46:11
除非明确要求您考虑排序算法,否则我建议您找到一个简单的排序算法并在代码中实现它。而不是“确定”你的代码不正确,只需测试一下并找出答案。 – alexis 2012-03-29 14:46:14