Issue
I have the following code where I am trying to create a sorting algorithm that finds the min and max elements in an array, exchanges those elements with the first and last elements in the array, and then reduces the array's size by 2 after excluding the two elements that are already in the proper positions, and repeats that process again until the array is sorted.
I am aware that one can use an int[] array as the main array, but I went with an ArrayList for this instead. After removing the two elements from the ArrayList, the program is supposed to find the next min and max, but for whatever reason, the min and max are still the previous elements that were supposedly removed. I even adjusted the left and right index variables.
How would I fix this issue?
public static int[] novel_sort(ArrayList<Integer> array) {
//array for sorted elements
int[] sorted = new int[array.size()];
//variables
int left = 0;
//int right = fully_sorted.length - 1;
int right = array.size() - 1;
int min = array.get(0); //both min and max initially start at first element
int max = array.get(0);
while (array.isEmpty() != true) {
//compare elements and interchange min and max until found
for (int i = 0; i < array.size(); i++) {
if (array.get(i) > max) {
max = array.get(i);
}
else if (array.get(i) < min || array.get(i) == min) {
min = array.get(i);
}
}
//insert elements into 'sorted' array
sorted[left] = min;
sorted[right] = max;
//remove elements
array.remove(array.indexOf(min));
array.remove(array.indexOf(max));
//decrement and increment the indices (going inward)
right--;
left++;
}
for (int i = 0; i <= (sorted.length - 1); i++) {
System.out.println(sorted[i]);
}
return sorted;
}
Solution
This initialization must be in the for loop:
int min = array.get(0); //both min and max initially start at first element
int max = array.get(0);
Some other considerations:
You should also consider when min and max are having the same value, what will you do in that scenario? The same value can be either pointing to same index, but it can also point to different index i.e. duplicated values.
Try to sort even number of integers, then try odd number of integers. Do both works?
Should you store the min max index instead of the min max value?
Answered By - fauzimh
Answer Checked By - Terry (JavaFixing Volunteer)