如何从未排序的数组中获取m个最小元素的索引,而不更改实际数组?

时间:2014-02-02 20:36:50

标签: java quicksort

我想创建一个临时数组来存储用户输入并对其进行排序以获取m个最小元素并引用originalArray的原始索引然后打印m个最小元素的索引但是当我运行时代码,我得到的只是-1。我的元素不应该超出原始数组的范围,因为它来自originalArray。为什么我会收到-1

import java.util.*;
public class MinimumSelection
{
    public static void main(String[] args)
    {
        //Array and variable declarations
        int[] originalArray;
        int[] tempArray;
        int tempValue;
        int lowestValue;
        int arrayLength;
        String elementValue;

        //Prompt the user for random numbers as an array input
        System.out.println("Please Enter your array length");
        arrayLength = Integer.parseInt(new Scanner(System.in).nextLine());
        //Input feeds as the length of the array as entered by user
        originalArray = new int[arrayLength];
        //Storing the input value in temporary array which will be used to sort
        tempArray = new int[arrayLength];

        //prompt user to enter elements of the orignial array
        for (int element = 0; element < originalArray.length; element++)
        {
            System.out.printf("\n Enter array elements %1$s: " + "\r\n", element + 1);
            elementValue = new Scanner(System.in).nextLine();
            originalArray[element] = Integer.parseInt(elementValue);
        }

        System.arraycopy(originalArray, 0, tempArray, 0, originalArray.length);

        //Sorting the original array
        for (int write = 0; write < tempArray.length; write++)
        {
            for (int sort = 0; sort < tempArray.length - 1 - write; sort++)
            {
                if (tempArray[sort] > tempArray[sort + 1])
                {
                    tempValue = tempArray[sort + 1];
                    tempArray[sort + 1] = tempArray[sort];
                    tempArray[sort] = tempValue;
                }
            }
        }

        //promoting user to enter no. of smallest elements they want this program to display
        System.out.println("Please Enter number of smallest element");
        lowestValue = Integer.parseInt(new Scanner(System.in).nextLine());

        //display output
        System.out.println("Result :");
        for (int loop = 0; loop < lowestValue; loop++)
        {
            int x = tempArray[loop];
            int y = Arrays.asList(originalArray).indexOf(x);
            // Arrays.asList(array).indexOf(4);

            System.out.println((new Integer(y)).toString());
        }
        new Scanner(System.in).nextLine();
    }
}

1 个答案:

答案 0 :(得分:0)

创建一个TreeMap,其中键是元素,值是原始数组中的索引。然后,您遍历此映射的条目,并在前m步之后跳出循环。