我正在尝试不使用arrays.sort对随机数数组进行排序。我有代码,但是没有用。不确定错误在哪里。任何帮助都将受到赞赏。
import java.util.*;
public class Sort
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("How many numbers do you want? ");
int howMany = in.nextInt();
int [] myArray = getRandomArray(howMany);
}
/* public static int bsearch(int[] arr, int key)
{
}*/
public static int[] getRandomArray(int howMany) {
int[] returnMe = new int[howMany]; // Assume size >= 0
Random rand = new Random();
for (int i = 0; i < howMany ; i++)
returnMe[i] = rand.nextInt(Integer.MAX_VALUE) + 1;
//System.out.print(returnMe[i] + " ");
for (int i = 1; i <= (howMany - 1); i++)
{
for (int j = 0; j < howMany - i -1; j++)
{
int tmp = 0;
if (returnMe[j] > returnMe[j+1])
{
tmp = returnMe[j];
returnMe[j] = returnMe[j + 1];
returnMe[j + 1] = tmp;
}
}
}
for ( int i = 0; i < howMany; i++)
System.out.println(returnMe[i] + " ");
return returnMe;
}
}
最佳答案
你的线
for (int j = 0; j < howMany - i -1; j++)
应该
for (int j = 0; j <= howMany - i -1; j++)
或者,删除“ -1”并保留“