patternjavaMinor
Sorting random non-repeating numbers
Viewed 0 times
randomsortingnonnumbersrepeating
Problem
I am working on a program in which 10000 random non-repeating numbers are selectively sorted into ascending order"
import java.util.Random;
public class Sorting {
public static void main (String[] args){
//Here, we initiate an array with the integers
//1 through 10,000 in order.
Random rgen = new Random();
int[] intArray = new int[10000];
for (int i=0; i=0; i--) {
max = i;
for (int j=i-1; j>=0; j--)
if (intArray[j]>intArray[max]) {
max = j;
}
//Here, we swap the positions of the
//maximum and the last value in the
//unsorted section of the list.
if (max != i) {
int tmp = intArray[i];
intArray[i] = intArray[max];
intArray[max] = tmp;
}
}
//Here, we output the result.
for (int k=0; k<10000; k++) {
System.out.println(intArray[k]);
}
}
}Solution
I tested it and it works as it should. I would only like to remark a couple of things.
You may want to split your long commented function into shorter ones:
-
-
-
-
print the result in the
This makes your code easier to read and easier to reuse.
Another thing I'd remove is the
Note: If you keep doing the swap as you do now, you won't have any problem by removing the
You may want to split your long commented function into shorter ones:
-
static int[] InitArray(int length){...}-
static int[] SelectionSort(int[]arr){...}-
static void Swap(int[]arr, int i, int j){...}-
print the result in the
main(), as you do know.This makes your code easier to read and easier to reuse.
Another thing I'd remove is the
if(max != i). I'd rather make the swap every time. If you look carefully, there's small chance that you do this operation unnecessarily, and when you do do it, it won't harm you. Note: If you keep doing the swap as you do now, you won't have any problem by removing the
if. However, if you modify it to make the swap without a temp variable, it might go wrong.Context
StackExchange Code Review Q#25576, answer score: 5
Revisions (0)
No revisions yet.