#### Java - Reverse Selection Sort

Total Post:51

Points:359

1711  View(s)
Ratings:
Rate this:

I am trying to create a program that does a selection sort but backwards. As in, finding the largest number and swapping it with the last. I have no idea why this isn't working.

UPDATED CODE according to comments.

```  import java.util.Scanner;
public class Problem20 {
public static void main(String[] args){
int data[] = new int;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter 10 numbers: ");
for (int i = 0; i < 10; i++)
{
data[i] = scan.nextInt();
}
sortBig(data);
}
public static void sortBig(int[] data){
int i, j, maxIndex, tmp;
for (i = data.length - 1; i >= 0; i--)           {
maxIndex = i;
for (j = i-1; j >=0; j--)
if (data[j] > data[maxIndex])
maxIndex = j;
if (maxIndex != i)
{
tmp = data[data.length - 1];
data[data.length - 1] = data[maxIndex];
data[maxIndex] = tmp;
}
}
for (int r = 0; r < data.length; r++){
System.out.print(data[r] + " ");
}
}
}```
1. ##### Re: Java - Reverse Selection Sort

Here is a simple test I wrote to find and make it easy to debug the code.

```import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class Problem20 {
@Test
public void testSorting() {
// passes
assertTrue(Arrays.equals(new int[]{1, 2, 3}, sortBig(3, 2, 1)));
// failed previously
assertTrue(Arrays.equals(new int[]{1, 2, 3, 4}, sortBig(4, 3, 2, 1)));
// create an array of unique values in pseudo random order
int[] largeArray = new int;
for (int i = 0; i < largeArray.length; i++)
largeArray[i] = (i * 29) % largeArray.length;
int[] sortedArray = sortBig(largeArray);
for (int i = 0; i < largeArray.length; i++)
assertEquals(i, sortedArray[i]);
}
public static int[] sortBig(int... data) {
for (int i = data.length - 1; i >= 0; i--) {
int maxIndex = i;
for (int j = i - 1; j >= 0; j--)
if (data[j] > data[maxIndex])
maxIndex = j;
if (maxIndex != i) {
//                int tmp = data[data.length - 1];
int tmp = data[i];
//                data[data.length - 1] = data[maxIndex];
data[i] = data[maxIndex];
data[maxIndex] = tmp;
}
}
return data;
}
}```

Modified On Mar-31-2018 05:24:46 AM