Java program sort random array
Thus, the purpose of this program is to selectively sort a random array of integers from largest to smallest. To do this, I needed to swap the first item with the largest item. I believe my methods are correct, but I am fairly new to Java and not sure what to call basically 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();
}
}
source to share
Also you can call the method sort()
inside the method printArray()
, 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);
}
...
source to share
Here is my code that I posted on Code Review. This array type is String, but you can put an integer instead. https://codereview.stackexchange.com/questions/160243/sort-a-given-string-in-ascending-order
The specified string
[H, B, D, G, F, E, A, C]
Output
[A, B, C, D, E, F, G, H]
public class sortArray {
public static void sort (String[] str)
{
int lastPos = str.length - 1;
int minPos = 0;
String s = "";
for (int i = 0; i < lastPos; i++)
{
minPos = i;
for (int j = i + 1; j <= lastPos; j++)
if (str[j].compareTo (str[minPos]) < 0)
minPos = j;
if (minPos != i)
{
s = str[i];
str[i] = str[minPos];
str[minPos] = s;
}
}
}
public static void main(String[] args){
String[] str = {"H", "B", "D", "G","F", "E", "A", "C"};
sort(str);
System.out.println(Arrays.toString(str));
}
}
source to share
you can use the built-in array function. Just call the built-in method and pass your array.
Arrays.sort (pass your array here).
If you want to use the built-in method, please refer to this link.
Java: sorting integer array without using Arrays.sort () array
source to share