I have an assignment to implementthe matrix class and a method that checks if the matrix is symmetric.
The method has to be recursive and then I have to calculate its complexity. After I have to transform the recursive function to its iterative version.
For now this is how my matrix class looks like:
public class Matrix<T> {
private int m, n;
private T[][] data;
public Matrix(int m, int n) {
this.m = m;
this.n = n;
}
public Matrix(T[][] data) {
this.data = data;
}
public boolean isSymmetric() {
if (m != n) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (data[i][j] != data[j][i]) {
return false;
}
}
}
return true;
}
return false;
}
public boolean isSymmetric(int i, int j) {
if (i < 0 && j < 0) return true;
else {
return isSymmetric(i - 1, j - 1);
}
}
public T get(int i, int j) {
return data[i][j];
}
public void set(int i, int j, T value) {
data[i][j] = value;
}
public int[] getSize() {
return new int[]{m, n};
}
#Override
public String toString() {
String rep = "";
for (int i = 0; i < m; i++) {
rep += "( ";
for (int j = 0; j < n; j++) {
rep += data[i][j].toString() + "\t";
}
rep += ")\n";
}
return rep;
}
}
I have a iterative version of the isSymmetric() function, but I cannot get the recursive one.
You can start check from maximum row and col each recursion will be decrese it by 1 until 0;
public class Matrix<T> {
private final int height;
private final int width;
private final T[][] data;
public Matrix(T[][] data) {
height = data.length;
width = data[0].length;
this.data = data; // it brakes OOP: encapsulation
}
public boolean isSymmetricIterative() {
if (height != width)
return false;
for (int row = 0; row < height; row++)
for (int col = 0; col < width; col++)
if (data[row][col] != data[col][row])
return false;
return true;
}
public boolean isSymmetricRecursive() {
return isSymmetricRecursive(height - 1, width - 1);
}
private boolean isSymmetricRecursive(int row, int col) {
return row < 0 && col < 0 || data[row][col] == data[col][row] && isSymmetricRecursive(row - 1, col - 1);
}
}
In the recursive version, you forgot to add a check to see if the two elements are equal. Without it, there is no case where the method would return false.
public boolean isSymmetric() {
return m == n && isSymmetric(m - 1, n - 1);
}
public boolean isSymmetric(int i, int j) {
if (i < 0 && j < 0) return true;
else if (data[i][j] != data[j][i]) return false;
else {
return isSymmetric(i - 1, j - 1);
}
}
Symmetric matrix is a square matrix that is equal to its transpose. Let's assume that we have a square matrix.
To avoid unnecessary iterations and to reduce the time complexity, you can iterate over the indices only in the lower left corner of the matrix and compare the corresponding elements with those in the upper right corner m[i][j]==m[j][i], excluding the main diagonal, until the first mismatch.
Try it online!
// let's assume that we have a square matrix
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4, 5},
{2, 3, 4, 5, 6},
{3, 4, 5, 6, 7},
{4, 5, 6, 7, 8},
{5, 6, 7, 8, 9}};
System.out.println(isSymmetric(matrix)); // true
System.out.println(isSymmetricR(matrix, 1, 0)); // true
}
// iterative version
static boolean isSymmetric(int[][] matrix) {
return IntStream.range(1, matrix.length)
.allMatch(i -> IntStream.range(0, i)
//intermediate output
.peek(j -> System.out.println("i=" + i + ",j=" + j))
.allMatch(j -> matrix[i][j] == matrix[j][i]));
}
// recursive version
static boolean isSymmetricR(int[][] matrix, int i, int j) {
if (i < matrix.length && j < i) {
//intermediate output
System.out.println("i=" + i + ",j=" + j);
if (matrix[i][j] == matrix[j][i]) {
if (j == i - 1) {
return isSymmetricR(matrix, i + 1, 0);
} else {
return isSymmetricR(matrix, i, j + 1);
}
} else {
// the first mismatch, the
// matrix is not symmetric
return false;
}
} else {
// if reached this point,
// the matrix is symmetric
return true;
}
}
The intermediate output is the same in both cases:
i=1,j=0
i=2,j=0
i=2,j=1
i=3,j=0
i=3,j=1
i=3,j=2
i=4,j=0
i=4,j=1
i=4,j=2
i=4,j=3
See also: How to remove rows and columns containing only zeros from a 2d matrix?
Related
There are various questions on how to find the number of cycles/circuits in a directed graph.I have mostly visited them, and i did come out with a code which does it.
I am struck at a point where my code doesn't give a cycle/circuit below of length 3.
Code:
public class CyclesInGraph {
// Graph modeled as list of edges
static int[][] graph =
{
{1, 2}, {2, 3}, {3, 4}, {4, 3},
{3, 1}
};
static List<int[]> cycles = new ArrayList<int[]>();
/**
* #param args
*/
public static void main(String[] args) {
for (int i = 0; i < graph.length; i++)
for (int j = 0; j < graph[i].length; j++)
{
findNewCycles(new int[] {graph[i][j]});
}
for (int[] cy : cycles)
{
String s = "" + cy[0];
for (int i = 1; i < cy.length; i++)
{
s += "," + cy[i];
}
o(s);
}
}
static void findNewCycles(int[] path)
{
int n = path[0];
int x;
int[] sub = new int[path.length + 1];
for (int i = 0; i < graph.length; i++)
for (int y = 0; y <= 1; y++)
if (graph[i][y] == n)
// edge refers to our current node
{
x = graph[i][(y + 1) % 2];
if (!visited(x, path))
// neighbor node not on path yet
{
sub[0] = x;
System.arraycopy(path, 0, sub, 1, path.length);
// explore extended path
findNewCycles(sub);
}
else if ((path.length > 2) && (x == path[path.length - 1]))
// cycle found
{
int[] p = normalize(path);
int[] inv = invert(p);
if (isNew(p) && isNew(inv))
{
cycles.add(p);
}
}
}
}
// check of both arrays have same lengths and contents
static Boolean equals(int[] a, int[] b)
{
Boolean ret = (a[0] == b[0]) && (a.length == b.length);
for (int i = 1; ret && (i < a.length); i++)
{
if (a[i] != b[i])
{
ret = false;
}
}
return ret;
}
// create a path array with reversed order
static int[] invert(int[] path)
{
int[] p = new int[path.length];
for (int i = 0; i < path.length; i++)
{
p[i] = path[path.length - 1 - i];
}
return normalize(p);
}
// rotate cycle path such that it begins with the smallest node
static int[] normalize(int[] path)
{
int[] p = new int[path.length];
int x = smallest(path);
int n;
System.arraycopy(path, 0, p, 0, path.length);
while (p[0] != x)
{
n = p[0];
System.arraycopy(p, 1, p, 0, p.length - 1);
p[p.length - 1] = n;
}
return p;
}
// compare path against known cycles
// return true, iff path is not a known cycle
static Boolean isNew(int[] path)
{
Boolean ret = true;
for(int[] p : cycles)
{
if (equals(p, path))
{
ret = false;
break;
}
}
return ret;
}
static void o(String s)
{
System.out.println(s);
}
// return the int of the array which is the smallest
static int smallest(int[] path)
{
int min = path[0];
for (int p : path)
{
if (p < min)
{
min = p;
}
}
return min;
}
// check if vertex n is contained in path
static Boolean visited(int n, int[] path)
{
Boolean ret = false;
for (int p : path)
{
if (p == n)
{
ret = true;
break;
}
}
return ret;
}
}
Output that I am getting:
1,3,2
But i should get 3,4 also as 3-4-3 also make a cycle in graph.
My solution for npuzzle works with 2x2 but stack over flow error with 3x3. I am not able to figure out whats wrong. I am using DFS to check if any of the path has the solution.
Algorithm,
- Move piece left, right, up & down.
- For each check if state is already visited .
- if not visited mark visited and check if it matches the goal state.
I believed that the stack should be able to hold all the states, it should be only 181400 states right?
Any help please!
public class PuzzleSolvable {
public static final int N = 3;
public static int[][] s2 = new int[][]{{8, 2, 1},
{-1, 4, 3},
{7, 6, 5}};
public static void main(String[] args) {
int[][] stage1 = new int[][]{ //needs 5 swaps
{1, 2, 3},
{4, 5, 6},
{7, 8, -1}
};
/*int[][] stage1 = new int[][]{{1, 2},
{4, -1}};
int[][] stage2 = new int[][]{{-1, 1},
{4, 2}};*/
Map<String, Boolean> map = new HashMap<>();
boolean solution = false;
for (int i = 0; i <= 181440; i = i + 3000) {
if (isSolvable(stage1, map, i)) {
solution = true;
break;
}
}
if (solution) {
System.out.println("Solution exists");
}else{
System.out.println("Solution does not exist");
}
}
static boolean isSolvable(int[][] s1, Map<String, Boolean> map, int depth) {
if (depth > 3000) {
return false;
}
depth++;
System.out.println(serializeArray(s1));
System.out.println(map.size());
if (map.get(serializeArray(s1)) != null) {
return false;
}
if (equals(s1, s2)) {
return true;
}
map.put(serializeArray(s1), true);
return isSolvable(move(s1, 0), map, depth) ||
isSolvable(move(s1, 1), map, depth) ||
isSolvable(move(s1, 2), map, depth) ||
isSolvable(move(s1, 3), map, depth);
}
static String serializeArray(int[][] arr) {
String s = "";
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
s = s + arr[i][j];
}
}
return s;
}
static boolean equals(int[][] s1, int[][] s2) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (s1[i][j] != s2[i][j]) {
return false;
}
}
}
return true;
}
static int[][] move(int[][] arr, int direction) {
int[][] array = new int[N][N];
int posx = 0, posy = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
array[i][j] = arr[i][j];
if (arr[i][j] == -1) {
posx = i;
posy = j;
}
}
}
switch (direction) {
case 0://right
if (posy < N - 1) {
System.out.println("Swap right");
swap(array, posx, posy, posx, posy + 1);
}
break;
case 1://left
if (posy > 0) {
System.out.println("Swap left");
swap(array, posx, posy, posx, posy - 1);
}
break;
case 2://up
if (posx > 0) {
System.out.println("Swap up");
swap(array, posx, posy, posx - 1, posy);
}
break;
case 3://down
if (posx < N - 1) {
System.out.println("Swap down");
swap(array, posx, posy, posx + 1, posy);
}
break;
}
return array;
}
static void swap(int[][] arr, int posx, int posy, int x, int y) {
int temp = arr[posx][posy];
arr[posx][posy] = arr[x][y];
arr[x][y] = temp;
}}
Edited:
Code updated with working version implemented using recursion depth limiter.
I think stack overflow does make sense.
If you test it with a target represented by
static int[][] s2 = new int[][]{
{ 1, 2, 3},
{ 4, -1, 5},
{ 6, 7, 8}
};
and set initial state to
int[][] stage5 = new int[][]{ //needs 5 swaps
{ 2, 3, 5},
{ 1, 4, -1},
{ 6, 7, 8}
};
which requires 5 swaps to get the target, isSolvable is invoked 54 times with no exception.
If you set initial state to
int[][] stage6 = new int[][]{ //needs 6 swaps
{ 2, 3, 5},
{ 1, 4, 8},
{ 6, 7, -1}
};
which requires 6 swaps to get the target, isSolvable is invoked about 12000 times, and throws StackOverflowError.
Even a simple rest like
recusiveTest(stage6, new Random());
//overflows after less than 5k invokes
private static boolean recusiveTest(int[][] array, Random rand){
System.out.println("counter " +isSolvedCounter++);
array[rand.nextInt(2)][rand.nextInt(2)] = 0;
return recusiveTest(array, rand);
}
throws StackOverflowError after less than 5000 runs.
A non recursive dfs solution would be more solid.
Here is a version with limited recursion depth. It needs profiling (it is slow) but it works (tested with a range of test cases. Not fully debugged though):
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class LimitedDfs {
private static final int DEPTH_LIMIT = 3000;
private static final int BLANK = 9;
private static int[][] directions = {
{-1, 0}, //up
{ 0,-1}, //left
{ 0, 1}, //right
{ 1, 0} //down
};
private static int[][] target = new int[][]{
{ 1, 2, 3},
{ 4, 5, 6},
{ 7, 8, 9}
};
private static State targetState = new State(target);
public static void main(String[] args) {
int[][] swap31 = new int[][] {
{3,5,1},
{6,2,4},
{8,7,9}
};
isSolvable(swap31);
}
static boolean isSolvable(int[][] stateData) {
State state = new State(stateData);
List<State> tested = new ArrayList<>();
LinkedList<State> toBeTested = new LinkedList<>();
toBeTested.add(state);
boolean solution = false;
System.out.print("working ");
while (! toBeTested.isEmpty()) {
if ( isSolvable(toBeTested, tested, 0)){
solution = true;
break;
}
System.out.print(".");
}
System.out.print(" Tested "+ tested.size() + " states. ");
if (solution) {
System.out.println("\n -> Solution exists ");
}else{
System.err.println("\n -> Solution does not exist ");
}
return solution;
}
static boolean isSolvable(LinkedList<State> toBeTested, List<State> tested, int depth) {
if((depth ++ > DEPTH_LIMIT) || toBeTested.isEmpty()) {
return false;
}
//else get last element in stack
State state = toBeTested.peek();
if (state.equals(targetState)) {
return true;
}
int added = 0;
for(int[] dir : directions) {
State newState = move(state, dir);
if((newState != null) && ! tested.contains(newState)) {
toBeTested.add(newState);
tested.add(newState);
added++;
break;
}
}
if(added == 0) { // means state was fully explored, remove it
toBeTested.remove(state);
}
return isSolvable(toBeTested, tested, depth);
}
private static State move(State state, int[] dir) {
int[][] stateData = state.getState();
int size = stateData.length;
int[][] newArray = new int[size][size];
int posY = 0, posX = 0;
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
newArray[y][x] = stateData[y][x];
if (stateData[y][x] == BLANK) {
posY = y;
posX = x;
}
}
}
if( isValidAddress(posY + dir[0], posX + dir[1], size, size)) {
swap(newArray, posY, posX,posY+ dir[0], posX+ dir[1]);
return new State(newArray);
}
return null;
}
private static void swap(int[][] arr, int y1, int x1, int y2, int x2) {
int temp = arr[y1][x1];
arr[y1][x1] = arr[y2][x2];
arr[y2][x2] = temp;
}
private static boolean isValidAddress(int rowIndex,int colIndex,
int numberOfRows, int numberOfCols) {
if((rowIndex <0) || (rowIndex >= numberOfRows)||
(colIndex <0) || (colIndex >= numberOfCols)) {
return false;
}
return true;
}
}
class State {
private final int[][] state;
private final int hash;
State(int[][] state) {
this.state = state;
hash = serializeArray(state).hashCode();
}
#Override
public boolean equals(Object obj) {
if (this == obj) { return true; }
if (obj == null) { return false; }
if (getClass() != obj.getClass()) {
return false;
}
return hash == obj.hashCode();
}
#Override
public int hashCode() {
return hash;
}
int[][] getState() {
return state;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(int[] array : state) {
sb.append(Arrays.toString(array))
.append("\n");
}
return sb.toString();
}
private static String serializeArray(int[][] array) {
StringBuilder sb = new StringBuilder();
for (int[] elements : array) {
for (int element : elements) {
sb.append(element);
}
}
return sb.toString();
}
}
An array is defined to be complete if all its elements are greater than 0 and all even numbers that are less than the maximum even number are in the array.
For example {2, 3, 2, 4, 11, 6, 10, 9, 8} is complete because
a. all its elements are greater than 0
b. the maximum even integer is 10 c. all even numbers that are less than 10 (2, 4, 6, 8) are in the array.
But {2, 3, 3, 6} is not complete because the even number 4 is missing. {2, 3, 4, 3, 6} is not complete because it contains a negative number.
Write a function named isComplete that returns 1 if its array argument is a complete array. Otherwise it returns 0
This is a question i have to solve but i am not able to find good logic for this questions . Here I have find maximum even numbers from the array in first loop and in second loop, i have to check all the even numbers less than the maximum even numbers and i am stuck on this. please help me ,,,,,,,,,,my code is below
public class Complete {
public static void main(String[] args) {
System.out.println(isComplete(new int[]{2,3,2,4,11,6,10,9,8}));
System.out.println(isComplete(new int[]{2,3,3,6}));
System.out.println(isComplete(new int[]{2,-3,4,3,6}));
}
private static int isComplete(int[] i) {
int set = 1;
int maxeven = 0;
int count = 0;
for(int a = 0; a < i.length; a++) {
if(i[a] < 0) {
set = 0;
break;
}
if(i[a]%2 == 0 && i[a] > maxeven) {
maxeven = i[a];
}
}
for (int c = 2; c <= maxeven; c=c+2) {
for( int b = 0; b<i.length; b++) {
if (c == i[b]) {
count++;
}
}
if (count > 0) {
set = 1;
} else {
set = 0;
break;
}
}
return set;
}
}
I have find maximum even numbers from the array in first loop and in
second loop, i have to check all the even numbers less than the
maximum even numbers
I have followed this logic and wrote this. I am checking the validity of condtion 1 (All elements >0) and in the same loop finding the largest even number.
In the second loop, I am checking whether all the even numbers lesser than the largest even nuber is present.
public class Complete {
public static void main(String[] args) {
System.out.println(isComplete(new int[] { 2, 3, 2, 4, 11, 6, 10, 9, 8 }));
System.out.println(isComplete(new int[] { 2, 3, 3, 6 }));
System.out.println(isComplete(new int[] { 2, -3, 4, 3, 6 }));
}
private static int isComplete(int[] i) {
int maxEven = 0;
for (int element : i) {
if (element <= 0) {
return 0;
}
if (element % 2 == 0) {
if (element > maxEven) {
maxEven = element;
}
}
}
for (int a = 2; a < maxEven; a = a + 2) {
if (!hasElement(i, a)) {
return 0;
}
}
return 1;
}
private static boolean hasElement(int[] i, int a) {
for (int element : i) {
if (element == a) {
return true;
}
}
return false;
}
}
Set count = 0 in the second loop, like this:
for(int c = 2; c<=maxeven;c=c+2){
count = 0;
for(int b = 0;b<i.length;b++){
That should solve your problem. Without count = 0, count will be >0 after you've looked for "2", so count>0 will be true when you look for "4" even if there are not "4"s.
int isComplete(int[] a) {
int max = 0;
for (int el: a) {
if (el <= 0) {
return 0;
}
if (el % 2 == 0) {
if (el > max) {
max = el;
}
}
}
int req = (max / 2) - 1;
int p = 0;
for (int c = 2; c < max; c = c + 2) {
for (int j = 0; j < a.length; j++) {
if (a[j] == c) {
p++;
}
}
}
if (req == p) {
return 1;
} else
return 0;
}
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 + " ");
}
}
So I am trying to make the following code into a recursive method, insertion sort, but for as much as I try I cannot. Can anyone help me?
public static void insertionSort(int[] array){
for (int i = 1; i < array.length; i++){
int j = i;
int B = array[i];
while ((j > 0) && (array[j-1] > B)){
array[j] = array[j-1];
j--;
}
array[j] = B;
}
}
EDIT:
I was thinking of something like this, but it doesn't look very recursive to me...
public static void insertionSort(int[] array, int index){
if(index < array.length){
int j = index;
int B = array[index];
while ((j > 0) && (array[j-1] > B)){
array[j] = array[j-1];
j--;
}
array[j] = B;
insertionSort(array, index + 1);
}
}
Try this:
public class RecursiveInsertionSort {
static int[] arr = {5, 2, 4, 6, 1, 3};
int maxIndex = arr.length;
public static void main(String[] args) {
print(arr);
new RecursiveInsertionSort().sort(arr.length);
}
/*
The sorting function uses 'index' instead of 'copying the array' in each
recursive call to conserve memory and improve efficiency.
*/
private int sort(int maxIndex) {
if (maxIndex <= 1) {
// at this point maxIndex points to the second element in the array.
return maxIndex;
}
maxIndex = sort(maxIndex - 1); // recursive call
// save a copy of the value in variable 'key'.
// This value will be placed in the correct position
// after the while loop below ends.
int key = arr[maxIndex];
int i = maxIndex - 1;
// compare value in 'key' with all the elements in array
// that come before the element key.
while ((i >= 0) && (arr[i] > key)) {
arr[i+1] = arr[i];
i--;
}
arr[i+1] = key;
print(arr);
return maxIndex + 1;
}
// code to print the array on the console.
private static void print(int[] arr) {
System.out.println();
for (int i : arr) {
System.out.print(i + ", ");
}
}
}
public static void insertionSort(int[] array, int index) {
if(array.length == index + 1) return;
insertionSort(array, index + 1);
// insert array[index] into the array
}
You can try this code. It works correctly.
public static int[] InsertionSort(int[] dizi, int n)
{
int i;
if (n < 1) {
InsertionSort(dizi, n - 1);
}
else {
int key = dizi[n];
i = n - 1;
while (i >= 0 && dizi[i] > key) {
dizi[i + 1] = dizi[i];
i = i - 1;
}
dizi[i + 1] = key;
}
return dizi;
}
for the recursion algorithm, we start with the whole array A[1..n], we sort A[1..n-1] and then insert A[n] into the correct position.
public int[] insertionSort(int[] array)
{
//base case
if(array.length==1) return new int[]{ array[0] };
//get array[0..n-1] and sort it
int[] arrayToSort = new int[array.length - 1]{ };
System.arraycopy(array, 0, arrayToSort, 0, array.length -1);
int[] B = insertionSort(arrayToSort);
//now, insert array[n] into its correct position
int[] C = merge(B, array[array.length - 1]);
return C;
}
private int[] merge(int[] array, int n)
{
int[] arrayToReturn = new int[array.length + 1] {};
int j = array.length-1;
while(j>=0 && n <= array[j])
{
arrayToReturn[j+1]=array[j;
j--;
}
arrayToReturn[j] =
}
Try below code by providing ele as an integer array, sortedIndex=index of first element and index=index of second element:
public static void insertionSort(int[] ele, int sortedIndex, int index) {
if (sortedIndex < ele.length) {
if (index < ele.length) {
if (ele[sortedIndex] > ele[index]) {
ele[sortedIndex] += ele[index];
ele[index] = ele[sortedIndex] - ele[index];
ele[sortedIndex] = ele[sortedIndex] - ele[index];
}
insertionSort(ele, sortedIndex, index + 1);
return;
}
if (index == ele.length) {
sortedIndex++;
}
insertionSort(ele, sortedIndex, sortedIndex + 1);
}
}
public static void sort(int[] A, int p, int r) {
if (p < r) {
int q = r - 1;
sort(A, p, q);
combine(A, p, q, r);
}
}
private static void combine(int[] A, int p, int q, int r) {
int i = q - p;
int val = A[r];
while (i >= 0 && val < A[p + i]) {
A[p + i + 1] = A[p + i];
A[p + i] = val;
i--;
}
}
public static void main(String... strings) {
int[] A = { 2, 5, 3, 1, 7 };
sort(A, 0, A.length - 1);
Arrays.stream(A).sequential().forEach(i -> System.out.print(i + ", "));
}
public class test
{
public static void main(String[] args){
test h = new test();
int a[] = { 5, 8, 9, 13, 65, 74, 25, 44, 67, 2, 1 };
h.ins_rec(a, a.length-1);
for(int i=0; i<a.length; i++)
log(a[i]);
}
void ins_rec(int a[], int j){
if( j == 0 ) return;
ins_rec(a, j - 1);
int key = a[ j ];
sort(a, key, j - 1);
}
void sort(int a[], int key, int i){
if( (i < 0) || (a[i] < key) ) {
a[ i + 1 ] = key;
return;
}
a[ i + 1 ] = a[ i ];
sort(a, key, i - 1);
}
private static void log(int aMessage){
System.out.println("\t\t"+aMessage);
}
}