Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In the class below, complete the evenOddSplit method so that any integer array p

ID: 3556925 • Letter: I

Question

In the class below, complete the evenOddSplit method so that any integer array passed into

the method will be sorted into even and odd segments with all even values proceeding all odd

values. The method will also return the array index where odd values start in the array. The

even and odd segments can contain evens and odds in any order and the runtime of the algorithm

cannot be worse than O(n).

/**   EvenOddSplit, COSC 236, Mock Final, Question 2   */

import java.util.*;

public class EvenOddSplit {

public static void main(String[] args) {

    int[] arr = {3, 5, 7, 9, 1, 12, 11, 6, 7, 4, 2, 14, 8, 21, 2};

    int oddStart = evenOddSplit(arr);

    System.out.println(Arrays.toString(arr));

    System.out.println("Odds start at array index: " + oddStart);

    // one possible output if sorting odd to the back:

    //   [2, 8, 14, 2, 4, 6, 12, 11, 7, 1, 9, 7, 5, 21, 3]

    // Odds start at array index: 7

}

public static int evenOddSplit(int[] list) {

        // Finish this method

}

private static void swap(int[] list, int a, int b) {

    int temp = list[a];

    list[a] = list[b];

    list[b] = temp;

}

}

Explanation / Answer

import java.util.*;
public class EvenOddSplit {
public static void main(String[] args) {
int[] arr = {3, 5, 7, 9, 1, 12, 11, 6, 7, 4, 2, 14, 8, 21, 2};
int oddStart = evenOddSplit(arr);
System.out.println(Arrays.toString(arr));
System.out.println("Odds start at array index: " + oddStart);
// one possible output if sorting odd to the back:
// [2, 8, 14, 2, 4, 6, 12, 11, 7, 1, 9, 7, 5, 21, 3]
// Odds start at array index: 7
}
public static int evenOddSplit(int[] list) {
   int i,len=list.length,j=0,pos=0;
   int k=len-1;
   for(i=0,k=len-1;i<k;)
   { if(list[i]%2==0)
       {i++;continue;}
   if(list[k]%2!=0)
   { k--;continue;}
       if(list[i]%2!=0&&list[k]%2==0)
           {swap(list,i,k);i++;k--;continue;}
  
   }
  
   for(i=0;i<len;i++)
       if(list[i]%2!=0)
           {pos=i;
   break;
}
   return pos;
}
private static void swap(int[] list, int a, int b) {
int temp = list[a];
list[a] = list[b];
list[b] = temp;
}
}