[英]Sort all even numbers in ascending order and then sort all odd numbers in descending order in a collection
[英]I want to sort only odd numbers in an array in ascending order and leaving even numbers at their orignal place in java
您需要考虑的关键方面是忽略数组中的偶数并仅将排序算法应用于奇数。 这是使用冒泡排序的实现:
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:尝试在这种直觉的基础上进行 nlogn 排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.