交替重新排列阵列

热梅塔:

给定正整数的排序数组。您的任务是替代地​​重新排列数组元素,即第一个元素应为最大值,第二个应为最小值,第三个应为第二个最大值,第四个应为第二个最小值,依此类推。

class RearrangeAlternate{
public void swapMax(int arr[], int i, int n){
    int x = arr[i];
    int j;
    for(j = n-1; j>i; j--){
        if(arr[j] > x){
            break;
        }
    }
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}
public void swapMin(int arr[], int i, int n){
    int x = arr[i];
    int j;
    int res = n-1;
    for(j = n-1; j>i; j--){
        if(arr[j] < x){
            if(arr[j] < arr[res]){
                res = j;
            }
        }
    }
    int temp = arr[i];
    arr[i] = arr[res];
    arr[res] = temp;
}
public void rearrange(int arr[], int n){
    for(int i = 0; i<n; i++){
        if(i%2 == 0){
            swapMax(arr, i, n);
        }
        else swapMin(arr, i, n);
    }
} 
}

请帮我找到错误

在某些情况下,它显示错误的输出。
例如。
82
12 23 28 43 44 59 60 68 70 85 88 92 124 125 136 168 171 173 173 179 199 212 230 277 282 306 314 316 325 328 336 337 363 365 368 369 371 374 387 387 394 414 422 427 430 435 457 457 493 493 527 527 531 538 541 546 568 583 650 691 730 737 751 764 778 783 785 789 794 803 809 815 847 858 863 874 887 896 916 920 926 927 930 957 981 997 997

我的代码输出:997 12 981 23 957 28 930 43 927 44 926 59 920 60 916 68 896 70 887 85 874 88 863 92 858 124 847 125 815 136 809 168 803 171 794 173 789 179 785 199 783 212 778 230 764 277 751 282 737 306 730 314 691 316 316 650 325 568 328 527 336 506 337 430430 363374369541541365583368531371371493387538394394457414435422546427

答案:997 12 981 23 957 28 930 43 927 44 926 59 920 60 916 68 896 70 887 85 874 88 863 92 858 124 847 125 815 136 809 168 803 171 794 173 173 789 179 785 199 783 212 212 778 230 764 277 751 282 737 306 730 314 691 316 650 325 583 328 568 336 546 337 541 363 538 365 531 368 527 527 369 371 493 374 457 457 387 435 394 430 414 427 427 422

Arvind Kumar Avinash:

由于您的数组已排序,因此您可以简单地执行以下操作:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int temp;
        for (int i = 0; i < arr.length; i++) {
            if (i % 2 == 0) {
                // Store the last element to 'temp'
                temp = arr[arr.length - 1];
                // Shift all elements, starting from index, 'i', to one place right
                for (int j = arr.length - 2; j >= i; j--) {
                    arr[j + 1] = arr[j];
                }
                // Put the value stored in 'temp' to index, 'i'
                arr[i] = temp;
            }
        }
        System.out.println(Arrays.toString(arr));
    }
}

输出:

[10, 1, 9, 2, 8, 3, 7, 4, 6, 5]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章