How should I go about sorting these?

I have 2 arrays.

example

array 1: [ 20, 10, 5, 15] these are the array elements

and

array 2: [ 3, 1, 0, 2] these are the expected index/positions of the elements in array 1

How should I go about doing it where if it matches the program will output "right" and if it doesn't it will output "wrong"?

sorry in advance if the question and grammar is a bit unclear (english isn't my first language)

2 answers

  • answered 2022-05-04 12:22 Alex Sveshnikov

    How would you check if array2 is correct yourself? You can check if the sequence of numbers, which you obtain from array1 using indexes from array2 is correctly sorted or not. For your example if you extract elements from array1 with indexes 3, 1, 0, 2 you will get a sequence of 15, 10, 20, 5. Is this a correctly sorted sequence? No. Why not? Because there are pairs of numbers where the second number is smaller than the first one (15 > 10, and 20 > 5). So, it gives you the following algorithm: keep iterating through array2 and extract elements from array1 with corresponding indexes. If at some step you extract a number which is smaller than a previous one - you can print "wrong" and stop. If you reach the end of array2 without such a situation to occur - then you can print "right".

  • answered 2022-05-04 13:30 Ilia Borisov

    If we assume that values are unique, you can use that.

        Integer[] arr1 = { 20, 10, 5, 15 };
        Integer[] arr2 = { 3, 1, 0, 2 };
        Integer[] tempArr = Arrays.copyOf(arr1, arr1.length); //create copy of arr1
        Arrays.sort(tempArr); 
    
        Integer[] outputArr = new Integer[arr1.length]; //create array to be filled with unsorted indicies
    
        for (int i = 0; i < tempArr.length; i++) {
            outputArr[i] = Arrays.asList(tempArr).indexOf(arr1[i]);
        }
    
        if (Arrays.equals(arr2, outputArr)) {
            return "right";
        }
        return "worng";
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum