Search code examples
javaarraysalgorithmsortingbubble-sort

Keeping indexes of an elements in the array after sorting in Java


I want that sorting array without actually changing its data. So I want only keep its indexes in another array. For this I use Bubble Sort algorithm, and at every swapping step I change elements of new array which keeps indexes of actual array. That's my code, but it doesn't work correctly

int[] bSort(int[] arrivalTimes) {
    int[] sequence = new int[arrivalTimes.length];
    for (int i = 0; i < sequence.length; i++) {
        sequence[i] = i;
    }

    for (int i = 0; i < arrivalTimes.length - 1; i++) {
        for (int j = i + 1; j < arrivalTimes.length; j++) {
            if (arrivalTimes[i] > arrivalTimes[j]) {
                int temp = sequence[i];
                sequence[i] = sequence[j];
                sequence[j] = temp;
            }
        }
    }
    return sequence;
}

So if input array is [2, 5, 1, 0, 4]

Then sequence array should be [3, 2, 0, 4, 1] (indexes of actual array)


Solution

  • You're forgetting to sort the actual array also. If the arrivalTimes array isn't sorted, your condition will not act the way you expect.

    int[] bSort(int[] arrivalTimes) {
        int[] sequence = new int[arrivalTimes.length];
        for (int i = 0; i < sequence.length; i++) {
            sequence[i] = i;
        }
    
        for (int i = 0; i < arrivalTimes.length - 1; i++) {
            for (int j = i + 1; j < arrivalTimes.length; j++) {
                if (arrivalTimes[i] > arrivalTimes[j]) {
                    int temp = sequence[i];
                    sequence[i] = sequence[j];
                    sequence[j] = temp;
                    
                    int temp2 = arrivalTimes[i];
                    arrivalTimes[i] = arrivalTimes[j];
                    arrivalTimes[j] = temp2;               
                }
            }
        }
        return sequence;
    }
    

    This is an inefficient solution though. I suspect this is part of some algorithms assignment so I'll leave the optimisations up to you.