How to put all even numbers in order first appear, and then odd numbers appear?

A

Awesome Boy

Guest
I having problem is how rearrange an array of int values so that all the even values appear before all the odd values in the order they appear. Need to check for any possible errors and throw an exception. Below is my coding:

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 % 2 == 0) {

// increment j by one
j++;

// swap the element
temp = arr;
arr = 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 + " ");
}
}


The error output show in the below:

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)


Actually I want the output like the below:

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)


Hope anyone can help me check the coding which part I wrong? Thanks a lot.

Continue reading...
 
Top