使用插入式列表仅分类奇数
我想使用给定数组中的插入排序对奇数进行排序,而不是触摸偶数数字,但是均匀数字的位置会更改我不希望它们在奇数
ex之间保持:
int arr[] = {1,4,5,2,7,6,3,9,0}
The output should be = {1,3,5,7,9,4,2,6,0}
这是我写的代码插入代码,但我无法弄清楚问题的奇数部分的排序,
我该如何在不进行排序的情况下将所有偶数数字放在右侧的所有均匀数字时,在左侧排序奇数数字?
public void InsertionOdd(int[] a) {
for (int i = 1; i < a.length; i++) {
int key = a[i];
int j = i - 1;
while(j >= 0 && a[j] > key) {
a[j+1] = a[j];
j = j - 1;
}
a[j + 1] = key;
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
}
I want to sort the odd numbers using insertion sort in a given array and not touch the even numbers but the even numbers' position will be changing I don't want them to stay between odd numbers
EX:
int arr[] = {1,4,5,2,7,6,3,9,0}
The output should be = {1,3,5,7,9,4,2,6,0}
This is my code where I wrote the insertion code but I couldn't figure out the sorting of only the odd part of the problem
How can I sort odd numbers on the left side in ascending order while putting all the even numbers on the right side without sorting?
public void InsertionOdd(int[] a) {
for (int i = 1; i < a.length; i++) {
int key = a[i];
int j = i - 1;
while(j >= 0 && a[j] > key) {
a[j+1] = a[j];
j = j - 1;
}
a[j + 1] = key;
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要更改两件事:
int key = a [i]之后添加验证; if(键%2 == 1)
现在代码应该起作用。
You need to change two things:
int key = a[i]; if( key % 2 == 1)
while (j >= 0 && (a[j] > key || a[j]% 2 == 0))
And now the code should work.
这是采用比较器的替代方法。
比较两个值
a
&amp;b
使用比较(a,b)
比较器返回-1,0,1
fora&lt; B,A == B和A&GT; b
分别。要为此方法构建一个比较器需要特别处理偶数的数字,以便将它们推到列表的尽头。由于所需的订单正在上升,比较(a,b)
必须返回-1
时a&lt; B
。为了强制为a
的偶数值,请使用a%2 == 0
必须返回1
。对于b
,b%2 == 0
必须返回-1
。a和b
的任何其他值都将取决于a.compareto(b)
的结果。可以使用比较器中的三元()运算符来实现这一点。因此,如果A甚至是A返回A
1
,则如果B为B,则返回A-1
,否则返回显式比较的结果。这是它在您的方法中的工作方式。
这样做有几个优势。
请注意,您可以将比较器直接编码到该方法中。但是,如果需要其他种类,它将不会那么通用。
Here is an alternative method that takes a comparator.
When comparing two values
a
&b
usingcompare(a,b)
the comparator returns-1, 0, 1
fora < b, a == b, and a > b
respectively. To build one for this method the comparator needs to treat even numbers specially so that they are pushed to the end of the list. Since the desired order is ascending,compare(a,b)
must return-1
whena < b
. To force that for even values ofa
, usea % 2 == 0
which must return a1
. Forb
,b % 2 == 0
which must return a-1
. Any other values ofa and b
will depend on the result ofa.compareTo(b)
. This can be achieved using the ternary (?:
) operator in the comparator.So if a is even, it returns a
1
, if b is even it returns a-1
, otherwise returns the result of the explicit compare.Here is how it works in your method.
Doing it like this has several advantages.
Note that you can code the comparator directly into the method. However, it will not be as versatile if other sorts are desired.