Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java program sort random array

So the purpose of this program is to selectively sort a random array of integers form largest to smallest. To do this, I needed to keep swapping the first element with the largest element. I think my methods are correct, but I am fairly new to Java and not sure what to call in main in order to execute my methods correctly. Thank you in advance!

 package sortarray;

 public class SortArray {

 public static int randomInt(int low, int high) { 
double e;
double x=Math.random();
e=low+x*(high-low);
return (int)e;
}
public static int[] randomIntArray(int n) { 
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 < a.length; i++) {
    if (a[i] > a[index]) {
        index = i;
    }
}
return index;
}

public static void swapElement(int[] a, int index1, int index2) {
    int temp = a[index1];
    a[index1] = a[index2];
    a[index2] = temp; 
}

public static void sort(int[] a) {
    int length = a.length;
    //use length-1 because do not need to swap last element with itself
    for (int i = 0; i < length-1; i++) {
        int indexOfMax = indexOfMaxInRange(a, i, length-1);
        swapElement(a, i, indexOfMax); 
    }
}

public static void printArray(int[] a) {
for(int i = 0; i < a.length; i++) {
    System.out.print(" " + a[i]);
}
}


public static void main(String[] args) {
 int[] array = randomIntArray(30);
    printArray();     
}

}
like image 361
Lauren McCabe Avatar asked Apr 10 '26 01:04

Lauren McCabe


2 Answers

To sort the array, you simply need to call the following:

sort(array);

Then, you can print the array again to verify that it is sorted with:

printArray(array);
like image 69
Jacob G. Avatar answered Apr 12 '26 14:04

Jacob G.


Also you can call the method sort() within of printArray() method, so when you call printArray() it will print sorted:

...
public static void printArray(int[] a) {
    sort(a);
    for (int i = 0; i < a.length; i++) {
        System.out.print(" " + a[i]);
    }
}


public static void main(String[] args) {
    int[] array = randomIntArray(30);
    printArray(array);
}
...
like image 38
JUAN CALVOPINA M Avatar answered Apr 12 '26 16:04

JUAN CALVOPINA M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!