本文介绍了未排序数组和已排序数组及其元素以相同顺序返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这是怎么回事,我有两个数组变量,其中一个变量的元素未排序,而另一个则是副本,以维护未排序和排序的数组只是使用一种而丢失另一种的信息。

I'm not sure what's going on here, I've got two array variables, one of them has its elements unsorted, while the other one is meant to be a copy in order to maintain both the unsorted and sorted arrays instead of just using one and losing the information in the other one.

public static void main(String[] args){
    int[] unsortedArray;
    int[] sortedArray;
    boolean continueProgram = true;
    Scanner inputScanner = new Scanner(System.in);
    String answer = new String();
    while (continueProgram == true) {
        unsortedArray = buildArray();
        sortedArray = unsortedArray;
        System.out.println(Arrays.toString(unsortedArray));
        quickSort(sortedArray, 0, sortedArray.length - 1);
        System.out.println(Arrays.toString(unsortedArray));
        returnPositions(sortedArray, unsortedArray);

这是我的代码,我使用快速排序对元素进行排序,但仅对变量 sortedArray ,而不是未排序的数组,因此我不知道为什么返回它,就像在打印时将其排序一样。

Here's my code, I've used a quicksort to sort the elements, but only on the variable sortedArray, not in unsorted array, so I don't know why it is returned as if it were sorted when I it is to be printed.

推荐答案

创建未排序数组的副本,然后再使用它进行排序:

Create a copy of your unsorted array before using it to sort:

sortedArray = new int[unsortedArray.length];
System.arraycopy( unsortedArray, 0, sortedArray, 0, unsortedArray.length );

在您撰写时:

sortedArray = unsortedArray;

实际上并没有创建数组的副本,只是将两个变量都设置为指向到同一数组-然后排序。

you aren't actually creating a copy of the array, you're just setting both variables to point to the same array - which you then sort.

这篇关于未排序数组和已排序数组及其元素以相同顺序返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 05:44