1

I'm try to check if the passed array is sorted or not:

public static boolean isSorted(int[] list){
    boolean isSorted = true;
    int[] arr = list;
    selectionSort(arr);

    for (int i = 0; i < list.length; i++) {
        if (arr[i] != list[i]){
            isSorted = false;
            break;
        }


        }
     return isSorted;
    }

I passed the array list and make array arr equal to list, what happened is the array list became equal to array arr after sorting.

What is java rules for that? and what should i do to separate arr from list?

  • 2
    `int[] arr = list;` doesn't copy the array. You'd need to use `int[] arr = list.clone();` or `int[] arr = Arrays.copyOf(arr, 0, arr.length);`. – Andy Turner Oct 25 '17 at 14:23

1 Answers1

4

int[] arr = list; doesn't copy the array, it just declares a variable which points to the same array instance.

You'd need to use int[] arr = list.clone(); or int[] arr = Arrays.copyOf(arr, 0, arr.length);.


But note that you don't need to sort an array to check if it is sorted: just check each element to see if the following element is smaller.

for (int i = 0; i < arr.length - 1; ++i) {
  if (arr[i + 1] < arr[i]) return false;
}
return true;
Andy Turner
  • 137,514
  • 11
  • 162
  • 243