How to sort two arrays by same index?

前端 未结 2 1756
臣服心动
臣服心动 2020-12-03 22:30

I have 2 arrays. I want to sort them by same index number. For example I have these:

int[] a = {120, 60, 50, 40, 30, 20};
int[] b = {12, 29, 37, 85, 63, 11};         


        
2条回答
  •  暖寄归人
    2020-12-03 22:52

    // a dirty and inefficient way of doing it, 
    // but should give you a heads up to get started
    
        // you obviously dont want to modify array b, so making a copy
        int[] c = Arrays.copyOf(b, b.length);
        // now apply a sort on 'c' and apply the same operation on 'a' when modifying 'c'
        // -> applying a bubble sort - > inefficient
        for( int i = 0; i < c.length ; i ++) {
            for( int j = 0 ; j < c.length - 1; j ++) {
                if(c[j] > c [j+1]) {
                    c[j] = c[j] + c[j+1];
                    c[j+1] = c[j] - c[j+1];
                    c[j] = c[j] - c[j+1];
    
                    // apply the same to a
                    a[j] = a[j] + a[j+1];
                    a[j+1] = a[j] - a[j+1];
                    a[j] = a[j] - a[j+1];
                }
            }
        }
    

提交回复
热议问题