简体   繁体   English

我只想按升序对数组中的奇数进行排序,并将偶数留在它们在 java 中的原始位置

[英]I want to sort only odd numbers in an array in ascending order and leaving even numbers at their orignal place in java

在此处输入图像描述

Below is the code in image where i have sorted array in ascending order but i am unable to sort only odd numbers, leaving even number at their original place like below [ 5 , 8, 6, 3 , 4] => [ 3 , 8, 6, 5 , 4]下面是图像中的代码,其中我已按升序对数组进行排序,但我无法仅对奇数进行排序,将偶数留在其原始位置,如下所示 [ 5 , 8, 6, 3 , 4] => [ 3 , 8 , 6, 5 , 4]

The key aspect you need to consider is that to ignore even numbers in array and apply your sorting algorithm at odd numbers only.您需要考虑的关键方面是忽略数组中的偶数并仅将排序算法应用于奇数。 Here's the implementing using bubble sort:这是使用冒泡排序的实现:

public static void main(String[] args) {
    int[] a = {5, 8, 6, 3, 4};
    int i, j, n=a.length;
    
    for(i=0; i < n; i++) {
        if (a[i]%2 != 0) {
            int toPlace = i;
            for(j=i+1; j < n; j++) {
                if (a[j]%2!=0 && a[i] > a[j]) {
                    toPlace = j;
                }
            }
            int temp = a[toPlace];
            a[toPlace] = a[i];
            a[i] = temp;
        }
    }
    
    for(i=0; i<n; i++) {
        System.out.println(a[i]);
    }
}

PS: Try building on this intuition for nlogn sorting. PS:尝试在这种直觉的基础上进行 nlogn 排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM