排序方法应返回一个字符串,该字符串以逗号分隔的整数列表,按升序排序。我的代码没有按4或更大的大小排序。如果没有system.out.println(),我也没有在控制台中获得返回类型的任何内容。任何建议/帮助表示赞赏。
import java.util.ArrayList;
public class Sorting {
public static void main(String[] args)
{
ArrayList<Integer> alInput = makeArray(5);
ArraySorter(alInput);
}
public static String ArraySorter (ArrayList<Integer> alSort)
{
if (alSort.size()<=1)
{
return String.valueOf(alSort.get(0)) ;
}
int iMin = alSort.get(0);
int iMinIndex = 0;
for (int i = 0;i<alSort.size();i++ )
{
if (alSort.get(i)<iMin)
{
iMin = alSort.get(i);
iMinIndex = i;
}
}
alSort.remove(iMinIndex);
System.out.println(String.valueOf(iMin) + ArraySorter (alSort));
return String.valueOf(iMin) + ArraySorter (alSort);
}
public static ArrayList<Integer> makeArray(int iSize)
{
ArrayList<Integer> alNum = new ArrayList<Integer>();
for (int i = 0; i<iSize;i++)
{
alNum.add((int )(Math.random() * 100 + 1));
}
System.out.println(alNum);
return alNum;
}
}
答案 0 :(得分:1)
为什么不尝试这种简单方法,
alInput.sort(null);
String myString = "";
for (int i=0;i<alInput.size();i++){
myString = myString + String.valueOf(alInput.get(i)) + ",";
}
myString= myString.substring(0,myString.length()-1);
System.out.println(myString);
答案 1 :(得分:0)
尝试一下:我添加了一些评论,解释了我为fixe所做的更改。希望它有所帮助:)
import java.util.ArrayList;
public class Sorting {
public static void main(String[] args)
{
ArrayList<Integer> alInput = makeArray(5);
// now you can get the sorted string :)
String sortedResult = ArraySorter(alInput);
System.out.println("The sorted array is : " + sortedResult);
}
public static String ArraySorter (ArrayList<Integer> alSort)
{
int iMin = alSort.get(0);
int iMinIndex = 0;
for (int i = 0;i<alSort.size();i++ )
{
if (alSort.get(i)<iMin)
{
iMin = alSort.get(i);
iMinIndex = i;
}
}
alSort.remove(iMinIndex);
// added this one in myself, this is your base case for preventing a stack overflow:
if (alSort.size() == 0) {
return String.valueOf(iMin);
}
return String.valueOf(iMin) + "," + ArraySorter (alSort); // changed from : String.valueOf(iMin) + ArraySorter (alSort);
}
public static ArrayList<Integer> makeArray(int iSize)
{
ArrayList<Integer> alNum = new ArrayList<Integer>();
for (int i = 0; i<iSize;i++)
{
alNum.add((int )(Math.random() * 100 + 1));
}
System.out.println(alNum);
return alNum;
}
}