lundi 26 octobre 2015

Store random integers in array

package selectionsortintro;

public class SelectionSortIntro {
public static void main(String[] args) {
int nums[] = {22, 30, 15, 1, 7, 87, 65, 24, 22, 0};

//print out unsorted list
for (int count = 0; count < nums.length; count++) {
  System.out.print(nums[count] + " ");
}
System.out.println("\n---------------------------------");
selectionSort(nums);

//print out sorted list
System.out.println("After sorting using the Selection Sort,"
  + " the array is:");
for (int count = 0; count < nums.length; count++) {
  System.out.print(nums[count] + " ");
 }
}

public static void selectionSort(int data[]) {
int smallest;
for (int i = 0; i < data.length - 1; i++) {
  smallest = i;
  //see if there is a smaller number further in the array
  for (int index = i + 1; index < data.length; index++) {
    if (data[index] < data[smallest]) {
      swap(data, smallest, index);
    }
   }
  }
 }

public static void swap(int array2[], int first, int second) {
int hold = array2[first];
array2[first] = array2[second];
array2[second] = hold;
 }
}

I want to add a random amount of random integers into the array, so the selection sort algorithm will sort them out. The only problem is, I don't know how to store the array with random numbers and not be a fixed amount. If that's confusing, when you make the array it's like :

int[] randomNumbers = new int[20];

Where 20 is the amount of numbers generated. Well I want to have the user be the judge of how many numbers are randomly generated into the array. So I'm thinking maybe use ArrayList? But then, I get confused as to how I can use it to add the random numbers into itself. If anyone can help me that'd be awesome




Aucun commentaire:

Enregistrer un commentaire