Adding data in Spiral order in Single dimensional Array

 Source Code:

package test;

public class InsertDataInSpiralOrder {

	public static void main(String[] args) {
		int row = 1;
		int col = 0;
		int matrixsize=8;
		int tempMatrixSize = matrixsize;
		int arr [] = new int[(matrixsize*matrixsize)+1];
		int trip = 0;
		int arrIndex = -1;
		
		for(int i = 1; i<=(matrixsize*matrixsize); i++){
			if (trip <=  (matrixsize/2-1)){
				if (col < tempMatrixSize){  //right direction
					col++;
					arrIndex= ((row*trip)*matrixsize)+(trip+col);
					arr[arrIndex] = i;
					continue;
				}else if (row < tempMatrixSize){ //down
					row++;
					arrIndex= ((row+trip)*matrixsize) - trip;
					arr[arrIndex] = i;
					continue;
				}else if (arrIndex > ((matrixsize*(matrixsize-trip)) - (matrixsize - (trip+1)))){ // left direction
					 arrIndex = arrIndex - 1;
					 arr[arrIndex] = i;
					 continue;
				}
				else if(arrIndex != (matrixsize*(trip+1))+(trip+1)){ // up
					arrIndex = arrIndex - matrixsize;
					arr[arrIndex] = i;
					continue;
				}else{ // done with the trip
				  if(trip ==  (matrixsize/2-1) && matrixsize%2!=0){ // handle odd order of matrix
					   arr[arrIndex+1] = i;
				   }else{
					   i--; // even order matrix
				   }
			   
				   trip++;
				   tempMatrixSize = tempMatrixSize - 2;
				   row = 1;
				   col = 0;
				}
			}
		}
		
		for(int i =1; i <=(matrixsize*matrixsize); i++){
			System.out.print("arr["+i+"]"+" = "+arr[i]+" ");
		}

	}

}
Add a comment