I have a Google foobar challenge:
Write a function called answer(data, n) that takes in a list of less than 100 integers and a number n, and returns that same list but with all of the numbers that occur more than n times removed entirely. The returned list should retain the same ordering as the original list - you don't want to mix up those carefully-planned shift rotations! For instance, if data was [5, 10, 15, 10, 7] and n was 1, answer(data, n) would return the list [5, 15, 7] because 10 occurs twice, and thus was removed from the list entirely.
And this was my answer:
public static int[] solution(int[] data, int n) {
// Your code here
int count,c=0;
int flag[]=new int[1000];
int b[]=new int[data.length];
for(int i=0;i<data.length;i++)
{ count=0;
if(flag[(data[i])]==0)
{
for(int j=0;j<data.length;j++)
{
if(data[i]==data[j])
count++;
}
if(count>n)
flag[(data[i])]=1;
else
{
flag[(data[i])]=2;
b[c++]=data[i];
}
}
else if(flag[(data[i])]==2)
{
b[c++]=data[i];
}
}
if(c==(data.length))
{
return b;
}
if(c==0)
{
int ne[]=new int[0];
return ne;
}
else
{
int ne[]=new int[c];
for(int k=0;k<c;k++)
{
ne[k]=b[k];
}
return ne;
}
}
It passed 8 test cases but is failing for the last test case and I am not able to figure out what could the test case since that one is a hidden case. Any idea?
Generally, when trying to find a problem, you run tests. I made your code fragment into a class I could teat.
I formatted your code to see more clearly what you were doing. Using more descriptive variable names would help. Also, don't rely on single statements of an if or a for loop not needing braces. The first time you try to add a line of code, forgetting that you left off the braces, well good luck debugging that.
Here's the test class I created. I couldn't find anything after trying about two dozen different values of N and input.
import java.util.Arrays;
public class GoogleChallenge {
public static void main(String[] args) {
int[] data = { 5, 10, 15, 10, 7, 888, 999, 999, 0 };
int n = 1;
System.out.println("input: n: " + n + " " + Arrays.toString(data));
System.out.println("Output: " + Arrays.toString(solution(data, n)));
}
public static int[] solution(int[] data, int n) {
// Your code here
int count, c = 0;
int flag[] = new int[1000];
int b[] = new int[data.length];
for (int i = 0; i < data.length; i++) {
count = 0;
if (flag[(data[i])] == 0) {
for (int j = 0; j < data.length; j++) {
if (data[i] == data[j]) {
count++;
}
}
if (count > n) {
flag[(data[i])] = 1;
} else {
flag[(data[i])] = 2;
b[c++] = data[i];
}
} else if (flag[(data[i])] == 2) {
b[c++] = data[i];
}
}
if (c == (data.length)) {
return b;
}
if (c == 0) {
int ne[] = new int[0];
return ne;
} else {
int ne[] = new int[c];
for (int k = 0; k < c; k++) {
ne[k] = b[k];
}
return ne;
}
}
}
Related
The twosum question is:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
I'm learning java and I'm going through some leetcode problems. I'm trying to come up with a brute force solution before I code for efficiency but my code won't seem to compile:
public class TwoSum
{
//static int[] arraynums = new int[]{2, 7, 11, 15};
//static int target = 9;
//public static void main(String args[])
//{
//TwoSum name = new TwoSum();
//name.twoSums(arraynums, target);
//}
public int twoSums(int[] nums, int target)
{
int sum = 0;
for (int i = 0; i < nums.length; i++)
{
for (int j = 0; j < nums.length; j++)
{
sum = nums[i] + nums[j];
if (sum == target)
{
System.out.println(i + " " + j);
return new int[] {i,j};
}
}
}
return new int[] {};
}
}
I know I need a return statement but I'm not sure what I should return and I'm also not sure if my main method is required.
#Alfabravo is right. you need to return an array of integer. If you don't want to return anything. just use
public void twoSum(int[] nums, int target)
You're on the right track!
In regards to adding a return statement, just add it after the println statement.
...
System.out.println(i + " " + j);
return new int[] {i,j};
...
although you need to check that i and j are not equal as they will point to the same number in nums if they are. Unless that isn't a requirement of the question. If it is you could add something like
if (sum == target && i != j)
good luck.
For leetCode you just need to complete the codes and no need to add a main function.
For your twoSum method you need to return an array with type int which contains the index of elements.
You can test like this:
public static void main(String args[]) {
int[] testData = {2, 7, 11, 15};
int target = 9;
TwoSum ts = new TwoSum();
int[] result = ts.twoSum(testData, target);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
public class Solution {
public int[] twoSum(int[] num, int target) {
// Take an array and the target number as parameter
// Initialize the variables
int length = num.length;
int index1 = 0;
int index2 = 0;
int i;
int j;
for (i=0; i<length; i++) {
// First loop, i starts at num[0] which is the first element in array
for (j=i+1; j<length; j++){
// Second loop, j starts at num[1], the second element
if (num[i] + num[j] == target){
// If they are equal return the index
index1 = i;
index2 = j;
}
}
}
// The result should be an array contains 2 indices
int[] result = new int[] {index1, index2};
return result;
}
}
Loop through each element x and find if there is another value that equals to target−x.
Just a small mistake when you're iterating in the next loop, just add j = i + 1. That will do it.
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i < nums.length; i++){
for(int j = i + 1; j < nums.length; j++){
if (nums[i] + nums[j] == target){
return new int[] { i,j };
}
}
}
return new int[] {};
}
class Solution {
public int[] twoSum(int[] numbers, int target) {
int first = 0, sec = numbers.length-1;
while(first!=sec){
if((numbers[first]+numbers[sec])==target)
break;
else if((numbers[first]+numbers[sec])>target)
sec--;
else
first++;
}
int res[] = new int[2];
res[0] = first+1;
res[1] = sec+1;
return res;
}
}
Given an array on numbers as input, remove all elements from the array which are either multiple of 3 or have the digit 3 in them. For e.g. 13 and 15 will be both removed from the array if they are present.
MyApproach
To remove 3, I have made function removeMultiple which first remove Multiple of 3 if it exist.And then I also made function removeDigit Which removes the digit 3 int it if the number is not multiple of 3.
But I am not getting expected output.
MyQuestion:What I am doing wrong in my code.Can anyone guide me?
#Edit:
boolean containsDigit3(int[] arr,int index)
{
boolean b1=false;
while(arr[index]>0)
{
int p=arr[index]%10;
if(p==3)
{
b1=true;
}
arr[index]=arr[index]/10;
}
if(b1==true)
return true;
else
return false;
}
boolean isMultipleOf3(int[] arr,int index)
{
boolean b1=false;
int p=arr[index]%3;
if(p==0)
{
b1=true;
}
if(b1==true)
return true;
else
return false;
}
public int[] remove(int[] arr)
{
// Array of max length
int p[] = new int[arr.length];
int count = 0;
for (int i = 0; i < arr.length; i++)
{
if (!isMultipleOf3(arr,i) && !containsDigit3(arr,i))
{
p[i] = arr[i];
++count;
}
}
// Array of right length - System.arraycopy not allowed?!
int[] q = new int[count];
for (int i = 0; i < q.length; ++i)
{
q[i] = p[i];
}
return q;
}
Parameters Actual Output Expected Output
'{24,27,30,31,34,37,40,42}' {0} {40}
Operating on full arrays might be more difficult than it has to be. Break down your code into small and accurate parts, don't mix up iterating and copying an array with checking-for-3-logic.
Consider this method to remove those unwanted elements:
public int[] remove(int[] arr) {
// Array of max length
int p[] = new int[arr.length];
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (!isMultipleOf3(arr[i]) && !containsDigit3(arr[i])) {
p[count] = arr[i];
++count;
}
}
// Array of right length - System.arraycopy not allowed?!
int[] q = new int[count];
for (int i = 0; i < q.length; ++i) {
q[i] = p[i];
}
return q;
}
Now you can focus on very, very simple methods for boolean isMultipleOf3(int i) and boolean containsDigit3(int i)
Here's some very basic implementations:
private boolean containsDigit3(int i) {
//indexOf returns position of character '3' in String that
//represents the number i. If '3' is not found it returns -1
//so indexOf('3') >= 0 is another way of saying "contains digit 3"
return Integer.toString(i).indexOf('3') >= 0;
}
private boolean isMultipleOf3(int i) {
return i%3 == 0;
}
I would write it like this
public int[] remove(int[] arr) {
return IntStream.of(arr)
.filter(i -> i % 3 != 0)
.filter(i -> !(""+i).contains("3"))
.toArray();
}
I have to hard code it.No inbuilt functions allowed.
In that case I would do something like the above except "hard coded"
public static int[] remove(int[] arr) {
int[] ret = new int[arr.length];
int count = 0;
OUTER:
for (int i : arr) {
if (i % 3 == 0)
continue;
int j = i;
while (j > 0) {
if (j % 10 == 3)
continue OUTER;
j /= 10;
}
ret[count++] = i;
}
// do the same as Arrays.copyOf(ret, count)
if (ret.length > count) {
int[] ret2 = new int[count];
for (int i = 0; i < count; i++)
ret2[i] = ret[i];
return ret2;
}
return ret;
}
so
int[] arr = {24, 27, 30, 31, 34, 37, 40, 42};
int[] arr2 = remove(arr);
System.out.println(Arrays.toString(arr2));
prints
[40]
I have implemented the select/median of medians algorithm using the following as a reference http://www.ics.uci.edu/~eppstein/161/960130.html (this has previously been linked here Median of Medians in Java).
My code seems to work for small arrays (~100) and even works for arrays of size 100001 http://pastebin.com/mwRc4Hig (answer 5008), but then fails on an input array of size 10001 http://pastebin.com/YwVBmgDk (answer 4960, my code outputs 4958).
Note that the correct answers for the texts above are equivalent to sorting the array and returning the element at array[array.length / 2], regardless of whether the array size is even or odd.
I'm not sure how to debug this issue. The functionality seems arbitrary and I'm just lost. Here below is my code:
public class MedianOfMedians {
public static void main(String[] args) {
MedianOfMedians mds = new MedianOfMedians();
mds.run();
}
private void run() {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] numArray = new int[n];
for (int i = 0; i < n; i++) {
numArray[i] = in.nextInt();
}
int median = select(numArray, numArray.length / 2);
System.out.print(median);
}
private int select(int[] numArray, int k) {
if (numArray.length <= 10) {
int[] sorted = insertionSort(numArray);
return sorted[k];
}
int divCount = (numArray.length % 5 == 0) ? numArray.length / 5 - 1 : numArray.length / 5;
int[] medOfMed = new int[divCount + 1];
int counter = 0;
int[] subArray;
while (counter <= divCount) {
subArray = splitByFive(counter, divCount, numArray);
medOfMed[counter] = select(subArray, subArray.length / 2);
counter++;
}
int M = select(medOfMed, numArray.length / 10);
List<Integer> lt = new ArrayList<>();
List<Integer> eq = new ArrayList<>();
List<Integer> gt = new ArrayList<>();
for (int i : numArray) {
if (i < M) {
lt.add(i);
} else if (i == M) {
eq.add(i);
} else {
gt.add(i);
}
}
if (k < lt.size()) {
return select(createArray(lt), k);
} else if (k > lt.size() + eq.size()) {
return select(createArray(gt), k - lt.size() - eq.size());
} else {
return M;
}
}
private int[] splitByFive(int splitIter, int divisions, int[] toSplit) {
int numToCopy;
if (splitIter == divisions) {
numToCopy = toSplit.length - (5 * splitIter);
} else {
numToCopy = 5;
}
int[] subArray = new int[numToCopy];
System.arraycopy(toSplit, splitIter * 5, subArray, 0, numToCopy);
return subArray;
}
private int[] createArray(List<Integer> list) {
int[] result = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
private int[] insertionSort(int[] numArray) {
for (int i = 1; i < numArray.length; i++) {
int j = i;
while (j - 1 >= 0 && numArray[j] < numArray[j - 1]) {
int temp = numArray[j];
numArray[j] = numArray[j - 1];
numArray[j - 1] = temp;
j--;
}
}
return numArray;
}
}
I don't have time to debug your code, but maybe I can offer a debugging technique for you to try yourself that's useful for recursive algorithms like this.
If there is an input that the algorithm fails on (and there is, as you found) then there is a smallest such input -- and the smaller this input, the easier it is to figure out what's going wrong. Because the algorithm is recursive, you have a nice way to isolate the first place that things go wrong: you can test that the result you are about to return from select() is correct (using a slow, trusted method like copying the data to a temporary buffer, sorting it and then grabbing the half-way element) just before returning the value. Doing this will be much easier if you rearrange the function to use just a single return statement, e.g.:
private int select(int[] numArray, int k) {
int knownCorrectAnswer = selectSlowlyButDefinitelyCorrectly(numArray, k);
int willReturn;
if (numArray.length <= 10) {
int[] sorted = insertionSort(numArray);
willReturn = sorted[k]; // Just remember what we will return
} else { // Need to add else branch here now
...
if (k < lt.size()) {
willReturn = select(createArray(lt), k);
} else if (k > lt.size() + eq.size()) {
willReturn = select(createArray(gt), k - lt.size() - eq.size());
} else {
willReturn = M;
}
} // End of inserted else branch
if (willReturn == knownCorrectAnswer) {
return willReturn;
} else {
yell("First problem occurs with numArray=<...> and k=<...>!");
}
}
yell() should print out the entire problem instance and halt the program (e.g. by throwing an exception). The nice thing about this setup is that you know that when yell() gets called, every call to select() that has already completed was correct -- since if it wasn't, yell() would have already been called and the program would have halted before now. So the output produced by yell() is guaranteed to be the first (not necessarily the smallest, but often that also) subproblem in which things went wrong.
Question: Define an array to be packed if all its values are positive, each value n appears n times and all equal values are in consecutive locations. So for example, {2, 2, 3, 3, 3} is packed because 2 appears twice and 3 appears three times. But {2, 3, 2, 3, 3} is not packed because the 2s are not in consecutive locations. And {2, 2, 2, 3, 3, 3} is not packed because 2 appears three times.
Write a method named isPacked that returns 1 if its array argument is packed, otherwise it returns 0. You may assume that the array is not null
If you are programming in Java or C#, the function signature is
int isPacked(int[ ] a)
public class isPackd{
public static void main(String[] args){
int result=isPacked(new int[ ] {2, 2, 1});
System.out.println("Return: " + result);
result=isPacked(new int[ ] {7, 7, 7, 7, 1, 7, 7, 7});
System.out.println("Return: " + result);
}//main()
public static int isPacked(int[ ] a){
for (int i=0; i<a.length; i++) {
int chkHowManyTimes=howManyTimes(a, a.length, a[i]);
if (chkHowManyTimes !=a[i]) {
return 0;
} // end of if
} // end of for
if (isConsecutive(a)==0) {
return 0;
} // end of if
return 1;
}//isPacked()
public static int howManyTimes(int[] array, int length, int findNumber){
int count=0;
for (int i=0; i<length; i++) {
if (array[i]==findNumber) {
count +=1;
} // end of if
} // end of for
//System.out.println(count);
return count;
}//howMany..()
public static int isConsecutive(int[] a){
//
//need help here to write code for this section
//
return 1;
}//isCon..()
}//class
I need help to check whether the number is in consecutive location or not.
And then,here is the full code below.
So, is there anything just feel free to ask here.
public class Consecutive
{
/***************************************************************************/
Author :- ShihabSoft
/***************************************************************************/
public static void main(String[] someArgs)
{
int[] args=new int[someArgs.length];
for(int i=0;i<someArgs.length;i++)
args[i]=Integer.parseInt(someArgs[i]);
int swit=checkArrConsecutive(args);
if(swit==0 || swit==1)
System.out.println("All "+args.length+" values appeared accordingly in the array");
switch(swit)
{
case 0:
System.out.println("Array is not well packed.");
break;
case 1:
System.out.println("Array is well packed");
}
}
//As per your needs we need two functions
static int checkArrConsecutive(int[] args)
{
int curr=0,temp=0;
if(args!=null)
{
int numIndex=0;
for(int i=0;i<args.length;i++)
{
curr=args[i];
temp=0;
if(checkNoccursNtime(args,curr)==0)
{
System.out.println("Sorry the number :- "+curr+" at index '"+i+"' repeats more or less than '"+curr+"' times");
return 2;
}
for(int j=numIndex;j<args.length;j++)
{
if(temp==curr)
break;
if(args[j]!=curr)
{
return 0;
}
else
temp++;
}
if(curr!=(args.length!=(i+1) ? args[i+1] : args[i]))
numIndex=i+1;
}
return 1;
}
return 0;
}
static int checkNoccursNtime(int[] args,int n)
{
if(args!=null)
{
int curr=0,temp=0;
temp=0;
curr=n;
for(int j=0;j<args.length;j++)
{
if(args[j]==curr && temp != curr)
temp++ ;
else if(args[j]==curr)
return 0;
}
return temp==curr ? 1 : 0;
}
return 0;
}
}
Just compile the above code and run passing values like this.
java Consecutive 5 5 5 5 5 1 2 2 3 3 3
public class Packed {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = { 7, 7, 7, 7, 7,7, 7 };
int tt = isPacked(a);
System.out.println(tt);
}
private static int isPacked(int[] a) {
int n;
int count = 0;
int k = 0;
int initialindex;
int finalindex = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] < 0) {
return 0;
}
n = a[i];
k = 0;
initialindex = i;
for (int j = 0; j < a.length; j++) {
k++;
if (n == a[j]) {
i++;
finalindex = k;
count++;
}
}
if (n != count || (finalindex - initialindex) != count) {
return 0;
}
i--;
count = 0;
}
return 1;
}
}
I had an interview question which i could not solve.
Write method (not a program) in Java Programming Language that will move all even numbers on the first half and odd numbers to the second half in an integer array.
E.g. Input = {3,8,12,5,9,21,6,10}; Output = {12,8,6,10,3,5,9,21}.
The method should take integer array as parameter and move items in the same array (do not create another array). The numbers may be in different order than original array. This is algorithm test, so try to give as efficient algorithm as you can (possibly linear O(n) algorithm). Avoid using built in functions/API. *
Also some basic intro to what is data structure efficiency
Keep two indices: one to the first odd number and one to the last even number. Swap such numbers and update indices.
(With a lot of help from #manu-fatto's suggestion) I believe this would do it:
private static int[] OddSort(int[] items)
{
int oddPos, nextEvenPos;
for (nextEvenPos = 0;
nextEvenPos < items.Length && items[nextEvenPos] % 2 == 0;
nextEvenPos++) { }
// nextEvenPos is now positioned at the first odd number in the array,
// i.e. it is the next place an even number will be placed
// We already know that items[nextEvenPos] is odd (from the condition of the
// first loop), so we'll start looking for even numbers at nextEvenPos + 1
for (oddPos = nextEvenPos + 1; oddPos < items.Length; oddPos++)
{
// If we find an even number
if (items[oddPos] % 2 == 0)
{
// Swap the values
int temp = items[nextEvenPos];
items[nextEvenPos] = items[oddPos];
items[oddPos] = temp;
// And increment the location for the next even number
nextEvenPos++;
}
}
return items;
}
This algorithm traverses the list exactly 1 time (inspects each element exactly once), so the efficiency is O(n).
// to do this in one for loop
public static void evenodd(int[] integer) {
int i = 0, temp = 0;
int j = integer.length - 1;
while (j >= i) {
// swap if found odd even combo at i and j
if (integer[i] % 2 != 0 && integer[j] % 2 == 0) {
temp = integer[i];
integer[i] = integer[j];
integer[j] = temp;
i++;
j--;
} else {
if (integer[i] % 2 == 0) {
i++;
}
if (integer[j] % 2 == 1) {
j--;
}
}
}
}
#JLRishe,
Your algorithm doesn't maintain the order. For a simple example, say {1,5,2}, you will change the array to {2,5,1}. I could not comment below your post as I am a new user and lack reputations.
public static void sorted(int [] integer) {
int i, j , temp;
for (i = 0; i < integer.length; i++) {
if (integer[i] % 2 == 0) {
for (j = i; j < integer.length; j++) {
if (integer[j] % 2 == 1) {
temp = y[i];
y[i] = y[j];
y[j] = temp;
}
}
}
System.out.println(integer[i]);
}
public static void main(String args[]) {
sorted(new int[]{1, 2,7, 9, 4});
}
}
The answer is 1, 7, 9, 2, 4.
Could it be that you were asked to implement a very basic version of the BubbleSort where the sort value of element e, where e = arr[i], = e%2==1 ? 1 : -1 ?
Regards
Leon
class Demo
{
public void sortArray(int[] a)
{
int len=a.length;
int j=len-1;
for(int i=0;i<len/2+1;i++)
{
if(a[i]%2!=0)
{
while(a[j]%2!=0 && j>(len/2)-1)
j--;
if(j<=(len/2)-1)
break;
a[i]=a[i]+a[j];
a[j]=a[i]-a[j];
a[i]=a[i]-a[j];
}
}
for(int i=0;i<len;i++)
System.out.println(a[i]);
}
public static void main(String s[])
{
int a[]=new int[10];
System.out.println("Enter 10 numbers");
java.util.Scanner sc=new java.util.Scanner(System.in);
for(int i=0;i<10;i++)
{
a[i]=sc.nextInt();
}
new Demo().sortArray(a);
}
}
private static void rearrange(int[] a) {
int i,j,temp;
for(i = 0, j = a.length - 1; i < j ;i++,j--) {
while(a[i]%2 == 0 && i != a.length - 1) {
i++;
}
while(a[j]%2 == 1 && j != 0) {
j--;
}
if(i>j)
break;
else {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
public void sortEvenOddIntegerArray(int[] intArray){
boolean loopRequired = false;
do{
loopRequired = false;
for(int i = 0;i<intArray.length-1;i++){
if(intArray[i] % 2 != 0 && intArray[i+1] % 2 == 0){
int temp = intArray[i];
intArray[i] = intArray[i+1];
intArray[i+1] = temp;
loopRequired = true;
}
}
}while(loopRequired);
}
You can do this with a single loop by moving odd items to the end of the array when you find them.
static void EvensToLeft(int[] items) {
int end = items.length;
for (int i = 0; i < end; i++) {
if (items[i] % 2) {
int t = items[i];
items[i--] = items[--end];
items[end] = t;
}
}
}
Given an input array of length n the inner loop executes exactly n times, and computes the parity of each array element exactly once.
Use two counters i=0 and j=a.length-1 and keep swapping even and odd elements that are in the wrong place.
public int[] evenOddSort(int[] a) {
int i = 0;
int j = a.length - 1;
int temp;
while (i < j) {
if (a[i] % 2 == 0) {
i++;
} else if (a[j] % 2 != 0) {
j--;
} else {
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
}
return a;
}
public class SeperatOddAndEvenInList {
public static int[] seperatOddAndEvnNos(int[] listOfNumbers) {
int oddNumPointer = 0;
int evenNumPointer = listOfNumbers.length - 1;
while(oddNumPointer <= evenNumPointer) {
if(listOfNumbers[oddNumPointer] % 2 == 0) { //even number, swap to front of last known even number
int temp;
temp = listOfNumbers[oddNumPointer];
listOfNumbers[oddNumPointer] = listOfNumbers[evenNumPointer];
listOfNumbers[evenNumPointer] = temp;
evenNumPointer--;
}
else { //odd number, go ahead... capture next element
oddNumPointer++;
}
}
return listOfNumbers;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int []arr = {3, 8, 12, 5, 9, 21, 6, 10};
int[] seperatedArray = seperatOddAndEvnNos(arr);
for (int i : seperatedArray) {
System.out.println(i);
}
}
}
public class ArraysSortEvensFirst {
public static void main(String[] args) {
int[] arr = generateTestData();
System.out.println(Arrays.toString(arr));
ArraysSortEvensFirst test = new ArraysSortEvensFirst();
test.sortEvensFirst(arr);
}
private static int[] generateTestData() {
int[] arr = {1,3,5,6,9,2,4,5,7};
return arr;
}
public int[] sortEvensFirst(int[] arr) {
int end = arr.length;
int last = arr.length-1;
for(int i=0; i < arr.length; i++) {
// find odd elements, then move to even slots
if(arr[i]%2 > 0) {
int k = findEven(last, arr);
if(k > i) swap(arr, i, k);
last = k;
}
}
System.out.println(Arrays.toString(arr));
return arr;
}
public int findEven(int last, int[] arr) {
for(int k = last; k > 0; k--) {
if(arr[k]%2 == 0) {
return k;
}
}
return -1; // not found;
}
public void swap(int[] arr, int x, int y) {
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
}
Output:
[1, 3, 5, 6, 9, 2, 4, 5, 7]
[4, 2, 6, 5, 9, 3, 1, 5, 7]
efficiency is O(log n).
public class TestProg {
public static void main(String[] args) {
int[] input = { 32, 54, 35, 18, 23, 17, 2 };
int front = 0;
int mid = input.length - 1;
for (int start = 0; start < input.length; start++) {
//if current element is odd
if (start < mid && input[start] % 2 == 1) {
//swapping element is also odd?
if (input[mid] % 2 == 1) {
mid--;
start--;
}
//swapping element is not odd then swap
else {
int tmp = input[mid];
input[mid] = input[start];
input[start] = tmp;
mid--;
}
}
}
for (int x : input)
System.out.print(x + " ");
}
}