1

I'm learning java and my program uses the sorting algorithms. The user can choose the size of the array. I learned to copy an array thanks to this question: Make copy of array Java

I copy the array like this:

    public static void main(String[] args) {
    int num = Integer.parseInt(JOptionPane.showInputDialog("Size of the array: ?"));
    int [] list = new int[num];
    for(int i=0;i<num;i++){
        int num2 = Integer.parseInt(JOptionPane.showInputDialog("Element: "+(i+1)));
        list[i]=num2;
    }
    int [] listCopy = Arrays.copyOf(list, list.length);

For my bubblesort I used the array saved inside list, for my selection sort I used the array saved inside my listCopy but when I tried to use the insertion sort with listCopy, the array was already sorted.

How can I copy an array so it never changes?

Community
  • 1
  • 1
user2737948
  • 329
  • 2
  • 10
  • 25
  • Can you please share the code for your bubble and insertion sorts? It's kind of hard to understand the issue without seeing the actual code. – Mureinik Sep 21 '14 at 18:19
  • @Mureinik I think he has sorted the arrays that he already has i.e. `list` and `listCopy` with 2 algorithm. He is new to programming and want to sort array with all his algos. – afzalex Sep 21 '14 at 18:23
  • You can create 1 more copy of array and work on it. – afzalex Sep 21 '14 at 18:24

2 Answers2

1

A copy of an array is simply another array, which behaves the same way as any other array: when you pass a copy to a sorting method, the copy becomes sorted, and remains sorted after that.

If you need to pass an unsorted array to multiple methods, make new copies as you go, like this:

int [] orig = new int[num];
for(int i=0;i<num;i++){
    int num2 = Integer.parseInt(JOptionPane.showInputDialog("Element: "+(i+1)));
    orig[i]=num2;
}
int [] copy = Arrays.copyOf(orig, orig.length);
bubbleSort(copy);
printArray(copy);
copy = Arrays.copyOf(orig, orig.length);
selectionSort(copy);
printArray(copy);
copy = Arrays.copyOf(orig, orig.length);
insertionSort(copy);
printArray(copy);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

You cannot create an immutable array, however you can create an immutable list:

List<Integer> immutableList = Collections.unmodifiableList(Arrays.asList(array));
cmd
  • 11,622
  • 7
  • 51
  • 61