Recently I have written a java program that executes selection sort on an array, however, it does not seem to return the correct output. What am I doing wrong?
Wanted output: [2.0, 3.7, 6.2, 7.4, 8.1, 8.5, 9.9, 15.7]
Actual output: [7.4, 2.0, 3.7, 6.2, 8.1, 8.5, 9.9, 15.7]
Code explanation: The method findMax finds the index of the largest object in the array, and the method process utilizes the method findMax to find the index of the largest number and swap it with the last, second-to-last, third-to-last, and so on term in order to put the array in order.
My code:
import java.util.Arrays;
import java.io.*;
public class Driver01
{
public static void main(String[] args)
{
//input
double[] myArray = {2.0, 3.7, 9.9, 8.1, 8.5, 7.4, 15.7, 6.2};
//sort the array
double[] sorted = process(myArray);
//output
System.out.println(Arrays.toString(sorted));
}
private static int findMax( int EndIndex, double[] enterArray) {
double max = 0;
int trueIndex = 0;
for( int x = 0; x < EndIndex; x++) {
if(enterArray[x] > max) {
max = enterArray[x];
trueIndex = x;
}
}
return trueIndex;
}
private static void swap(int swap1, int swap2, double[] enterArray) {
double temp = 0;
temp = enterArray[swap1];
enterArray[swap1] = enterArray[swap2];
enterArray[swap2] = temp;
}
private static double[] process(double[] enterArray) {
int range = enterArray.length -1;
for( int x = 0; x < enterArray.length; x++) {
int j = findMax(range, enterArray);
swap(j, range, enterArray);
range = range -1;
}
return enterArray;
}
}
When you call:
int j = findMax(range, enterArray);
in process(), range is defined as
int range = enterArray.length-1
So your findMax() function is not going through the entire array
You can fix this by changing your for loop in findMax() function to:
for (int x = 0; x < EndIndex+1; x++) {
...
}
There is probably a more elegant solution, but that is the problem in your code
EDIT:
A better solution would be to change your process() function to:
private static double[] process(double[] enterArray) {
int range = enterArray.length;
System.out.println("Array Length: " + enterArray.length);
for (int x = 0; x < enterArray.length; x++) {
int j = findMax(range, enterArray);
swap(j, range-1, enterArray);
range--;
}
return enterArray;
}
This way, findMax() is able to cycle through the full range of the array and swap is able to access the last element of the array. range is decremented since the max number is now the last element of the array. This is easier to understand from an outside perspective than my original answer.