手动以升序排列数组 [英] Manually Sorting an Array in Ascending Order
问题描述
我有一个家庭作业,以升序排列的数组。显然,这是需要手动完成,而无需使用任何的排序()
功能。
I have a homework assignment to sort an array in ascending order. Obviously, this is to be done manually without using any kind of sort()
function.
我想做到这一点,我需要两个为
循环:通过现有的数组第一个将循环,并创建具有的价值和指数临时值数组。第二个循环将临时值进行比较,以现有的值,并对其进行排序。我一直想写的code,但我似乎无法得到它的权利。这里是我想出了最新的方法:
I figured to do it, I would need two for
loops: the first one will loop through the existing array and create a temporary value with the value and index of the array. The second loop will compare the temporary values to the existing values and sort them. I keep trying to write the code, but I just can’t seem to get it right. Here is the latest method I came up with:
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;
}
我是pretty肯定,这是不正确的,但如果有人可以把我在正确的方向将是非常美联社preciated!
I’m pretty sure this is incorrect, but if someone could push me in the right direction it would be very appreciated!
推荐答案
您有选择排列。你必须在 X + 1
,而不是 0 $ C开始你的
是
$ C>。否则,你正在重新扫描该阵列的排列部分。还应该注意的是选择排序是原地算法;如果你正在寻找做出的复制的数组,你应该使用 Arrays.copy
方法,否则 INT [] newArray = inArray;
正在创建一个别名,而不是一个副本。最后,在嵌套循环的如果
语句应的交换的 A [X]
和 A [Y]
,不能简单地把 tempValue
在
You have a nearly OK version of the Selection Sorter. You need to start your y
at x+1
, not at 0
. Otherwise you're re-scanning the sorted portion of the array. You should also note that selection sort is an in-place algorithm; if you are looking to make a copy of the array, you should use Arrays.copy
method, otherwise int[] newArray = inArray;
is creating an alias, not a copy. Finally, the if
statement in the nested loop should swap a[x]
and a[y]
, not simply put tempValue
in:
if(newArray[x] < newArray [y]) {
int tempValue = newArray[y];
newArray[y] = newArray[x];
newArray[x] = tempValue;
}
这篇关于手动以升序排列数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!