👋

ITスクール DAY10 整列アルゴリズム(Insertion)/多次元配列

2023/07/19に公開

整列アルゴリズム

挿入ソート(Insertion sort)

Insertion Sort

public class InsertSort {

	public static void main(String[] args) {
		
		int[] a = new int[] {11,23,7,9,14};
		
		int key=0, prev = 0;
		
		for(int i =1; i < a.length; i++) {   
			    key = a[i];
			    prev = i-1;
			
			while(prev>=0 && a[prev]>key) {
				a[prev+1] = a[prev];
				prev--;
			}
			
		        a[prev+1] = key;
		  }
		
		
		for(int i : a) {
			System.out.print(i+" ");
		}
     } 
	
}	

最高:時間計算量:O(N)
平均・最悪:時間計算量:O(N^2)

多次元配列

ArrayEx13

public class Array13Ex {

public static void main(String[] args) {
		
int [][] score = {
	           {80,80,80},	    
		   {90,90,90},	
		   {75,75,75},
		   {95,95,95},
		   {60,60,60}
		}; 
		
int[] stdTotal = new int[5]; 
float[] stdAvg = new float[5]; 
int[] subTotal = new int[3]; 
float[] subAvg = new float[3]; 
		
		
for(int i=0; i<score.length; i++) {
   for(int j=0; j<score[i].length; j++) {
		stdTotal[i]  += score[i][j];
    } 
    stdAvg[i] = (float)stdTotal[i]/(float)score[i].length;
			
    subTotal[0]+= score[i][0];
    subTotal[1]+= score[i][1];
    subTotal[2]+= score[i][2];
			    
			
    if(i==4) {
        for(int y=0; y<subAvg.length; y++) {
	subAvg[y] = (float)subTotal[y]/(float)score.length;
	}				
       }		
   }	
		
System.out.printf("학생 개인별 종점 : ");
for(int a: stdTotal) {
  System.out.print(a+" ");
 }
		  
System.out.println();
		  
 System.out.printf("학생 개인별 평균 : ");
 for(float a: stdAvg) {
     System.out.print(a+" ");
   }
		  
System.out.println();
		
System.out.printf("과목별 종점     : ");
for(int a: subTotal) {
	System.out.print(a+" ");
   }  
		  
System.out.println();
		  
System.out.printf("과목별 평균     : ");
 for(float a: subAvg) {
	 System.out.print(a+" ");
   }
		
  }

}

Discussion