0

我正在尝试创建一个执行选择排序但向后的程序。如,找到最大的数字并将其与最后一个交换。我不知道为什么这不起作用。

根据评论更新代码。

  import java.util.Scanner;


public class Problem20 {


    public static void main(String[] args){

        int data[] = new int[10];
        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] + " ");
        }


    }


}
4

2 回答 2

0

您需要反转您的第一个 for 循环 -for(int i = data.length - 1; i >= 0; i--)

您还需要修改第二个 for 循环以反映第一个 for 循环中的更改(循环内部看起来不错,但循环初始化块需要更正)

于 2013-04-22T20:39:19.470 回答
0

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[1000];
        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;
    }
}

The simplest list I found which failed to sort was 4,3,2,1 and by debugging it I could see you were always swapping with the last element, not the last element data.length -1 being searched i after making that substitution the tests worked even for a large array.

于 2013-04-23T05:51:25.470 回答