2012-04-26 66 views
0

这里是我当前的代码:如何获取手动输入数组并对其进行排序?

public static void main (String [] args) 
{ 
try 
     { 
     System.out.println("Please enter the amount of numbers in the array"); 
     int arraySize2 = keyboard.nextInt(); 
     System.out.println("Please enter the numbers in the array seperately."); 
     int[] array = new int[arraySize2]; 
     for(int b=0; b<=arraySize2-1; b++){ 
      array[b] = keyboard.nextInt(20);}  
     for (int i = 0; i < array.length -1; i++){ 
      int minPos = i; 
      for (int j = i; j < array.length; j++){ 
      if (array[j] < array[minPos]) 
       minPos = j; }  
      // swaps minimum value with current location 
      int temp = array[i]; 
      array[i] = array[minPos]; 
      array[minPos] = temp; } 
     } 
     catch(ArrayIndexOutOfBoundsException e) 
     { 

     } 
} 

,我认为我的问题是什么地方,当我手动输入数组。但是我在那里朦胧?有没有人看到问题?我基于一个随机数组并将其排序的方法基于此代码。谢谢。

+1

'keyboard.nextInt(20);'以20为基数读取数字 - 你确定要这样吗?除此之外,代码没有问题(当然,格式除外)。你可以使用'Arrays.sort()'而不是手动选择排序。 – Anthales 2012-04-26 21:53:30

+0

@Anthales,但这可能是家庭作业,所以'Arrays.sort()'不允许:) – ant 2012-04-26 22:36:35

回答

0

为什么你不使用TreeMap<Integer, Integer>并不断输入值。最后使用迭代器或for each循环以后打印或使用这些数字。

或者您可以使用二叉搜索树并不断向其中插入数据。最后做一个有序的遍历。

相关问题