I have to implement a Selection Sort in Java according to these parameters:
Implement a variation to the SelectionSort that locates both the smallest and largest elements while scanning the list and positions them at the beginning and the end of the list, respectively. On pass number one, elements x0,...,xn-1 are scanned; on pass number two, elements x1,...,xn-2 are scanned; and so on.
I am passing the method an array of size 32, and when I print the array it is not sorted. What's the matter with my code?
static void selectionSort() {
scramble();
int smallIndex = 0; //index of smallest to test
int largeIndex = array.length - 1; //index of largest to test
int small = 0; //smallest
int large; //largest
int smallLimit = 0; //starts from here
int largeLimit = array.length - 1; //ends here
int store; //temp stored here
int store2;
for(int i = 0; i < array.length/2; i++) { //TODO not working...
small = array[smallLimit];
large = array[largeLimit];
for(int j = smallLimit; j <= largeLimit; j++) {
if(array[j] < small) {
smallIndex = j;
small = array[j];
}
else if(array[j] > large) {
largeIndex = j;
large = array[j];
}
}
store = array[smallLimit];
store2 = array[smallIndex];
array[smallLimit] = store2;
array[smallIndex] = store;
store = array[largeLimit];
array[largeLimit] = array[largeIndex];
array[largeIndex] = store;
smallLimit++;
largeLimit--;
}
print();
}
Like @Joni, clearly pointed out, there is big caveat with swapping two elements twice during a traversal of the array. Since you have to implement the sorting algorithm in-place, you need to take into account the positions of the elements to be swapped as it happens in succession.
Another limiting case that you need to see is when there are just three elements left i.e. the last iteration of the
for
loop. This is how I would go about it:Working DEMO for the snippet mentioned above, building upon your code. Hope it gets you started in the right direction.
Think about the extreme cases: what happens when the largest or smallest item is found at
smallLimit
orlargeLimit
. When that happens you have two problems:largeIndex
andsmallIndex
are not set. They maintain their values from a previous iteration.These problems are easy to fix. You could have avoided the problem following a few guidelines:
small
usingsmallIndex
, if you just usedsmallIndex
there would be no danger of different variables falling out of step.smallIndex
was declared in the loop body and not outside the compiler would have told you there's a chance it was not set before the swap.