I'm unsure how do I call my code so that it matches my randomizer. My randomizer basically generates a number of random integers in an array and prints them like so.
I tried using the insertion sort implementation i grabbed from geeks4geeks. They all have the parameter int[arr].
This is my code
public class randomArr {
public void randomizer(){
Scanner sc = new Scanner(System.in);
Random r = new Random();
System.out.println("Please enter the amount of integers you want in your array: ");
int n = sc.nextInt();
// Create array of 1000 ints
int[] intArr = new int[n];
// Fill array with random ints
for ( int i = 0; i < intArr.length; i++) {
intArr[i] = r.nextInt(100);
System.out.print(intArr[i] + ", ");
}
}
}
This is what i want to happen basically:
As you can see im calling sort and print array with my "intArr". How do i call my method with the given methods?
I have commented out the object i made using my method but if i were to leave it in, how would i use that object to call sort() and printarray()?
public class insertionSort {
public static void main(String[] args){
//randomArr arry = new randomArr(); \\the object of my method
//arry.randomizer());
Scanner sc = new Scanner(System.in);
Random r = new Random();
System.out.println("Please enter the amount of integers you want in your array: ");
int n = sc.nextInt();
// Create array of 1000 ints
int[] intArr = new int[n];
// Fill array with random ints
for ( int i = 0; i < intArr.length; i++) {
intArr[i] = r.nextInt(100);
System.out.print(intArr[i] + ", ");
}
sort(intArr);
printArray(intArr);
}
public static void sort(int arr[]){
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + ", ");
System.out.println();
}
}
Aucun commentaire:
Enregistrer un commentaire