-4

この割り当てでは、最後のメソッドを再びループさせて、一連の乱数で次に大きな要素を見つけることができません。この問題を解決するためのいくつかの入力は素晴らしいでしょう。ありがとうございました。

public static void main(String[] args) {

    int[] array = randomIntArray (10);   
    sortArray (array);

}

  public static int randomInt (int low, int high){ // Create a serie of random numbers
    int x = 0;
    for (int i = 0; i < 10; i++){
        x = (int)(Math.random ()* (high - low) +low);

    }  
    return x;

}
public static int[] randomIntArray (int n) { // Size of array
    int[] a = new int [n];
    for (int i = 0; i <a.length; i++){
        a[i] = randomInt (-5, 15);
    }
    return a;
}

public static int indexOfMaxInRange (int[] a, int low , int high){

    int index = low;
    for (int i = low +1; i < high; i++){
        if (a[i] > a[index]){ // If the position of i is greater than index
            index = i; // then index will equal that position with the highest element
        }         
    }  
  return index;


}
public static int swapElement (int []a, int index , int i){
    int tmp =0;

  for(i = 0; i < (a.length); i++) {
    tmp = index;
     a[i]= a[tmp] ;
  } 
    return a[tmp] ;
}

public static void sortArray (int[] array){ //The sortArray calls the indexOfMaxInRange to get the index of the largest element, then uses swapElement to swap that index's position to position a[i].

    for (int b= 0; b <array.length; b++){ 
    System.out.println (array[b]+"\t"+ b); // Print out original list of random numbers
    }
    System.out.println ();

    for (int i = 0; i <array.length; i++){    
    int index = indexOfMaxInRange (array, 0, 10 );
    int sort = swapElement (array, index, 0);

    System.out.println (sort+"\t"+ i);      
    }

}
4

2 に答える 2

0

最後の 3 つの方法に加えられた変更

public static int indexOfMaxInRange (int[] a, int low , int high){

    int index = low;
    for (int i = low +1; i < a.length; i++){
        if (a[i] > a[index]){ // If the position of i is greater than index
            index = i; // then index will equal that position with the highest element
        }         

    }  
  return index;


}
public static void swapElement (int []a, int index , int i){
    int pos2;        
    pos2 = index;
     a[i]= a[pos2];  

     System.out.println (a[i]+"\t"+ index);     
}

public static void sortArray (int[] array){ 
    for (int b= 0; b <array.length; b++){ 
    System.out.println (array[b]+"\t"+ b);
    } 
    System.out.println ("Number in order");     


    for (int i = 0; i <array.length-1; i++){    
    int index = indexOfMaxInRange (array, i, 10 );
    swapElement (array, index,i );
    }

}
于 2013-04-19T03:31:28.690 に答える