我遇到的问题是如何重新排列 int 值数组,以便所有偶数值出现在所有奇数值之前。下面是我的编码:
import java.io.*;
public class EvenAppearBeforeOdd {
// function to rearrange the array in given way.
static void rearrangeEvenAndOdd(int arr[], int n)
{
// variables
int j = -1,temp;
// quick sort method
for (int i = 0; i < n; i++) {
// if array of element
// is odd then swap
if (arr[i] % 2 == 0) {
// increment j by one
j++;
// swap the element
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
// Driver code
public static void main(String args[])
{
int arr[] = { 15, 9, 1, 3, 10, 5, 4, 8 };
System.out.println("\n\nBefore\n");
System.out.println(arr[]);
try {
System.out.println(EvenAppearBeforeOdd.rearrangeEvenAndOdd(arr);
} catch (Exception e) {
System.out.println("Error!!!");
}
int n = arr.length;
rearrangeEvenAndOdd(arr, n);
System.out.println("\n\nAfter\n");
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
}
错误输出如下所示:
run:
C:\Users\User\AppData\Local\NetBeans\Cache\8.0.2\executor-snippets\run.xml:48:
Cancelled by user.
BUILD FAILED (total time: 3 seconds)
实际上我想要如下的输出:
run:
Before
15 9 1 3 10 5 4 8
After
10 4 8 3 15 5 9 1 BUILD SUCCESSFUL (total time: 0 seconds)
希望有人能帮我检查一下我的代码哪部分错了?多谢。
holdtom
偶然的你
萧十郎
相关分类