`

插入排序

 
阅读更多

代码:

int[] scores = {2,3,1,10,20,4,5,8,6,7,3};
	    int i,j,temp = 0;
	    //排序
	    for(i=1;i<scores.length;i++){
	      if(scores[i] < scores[i-1]){
	    	temp = scores[i];
	    	j = i-1;
		    do{
		    	scores[j+1] = scores[j];
		    	j--;
		    }while(j>=0&&temp<scores[j]);
	    	scores [j+1] = temp;
	      }
	    }
	    //打印排序后的结果
	    for(int l=0;l<scores.length;l++){
	    	System.out.println(scores[l]);
	    }

 另外一种写法:(for循环从i=0开始)

      

int[] s = {20,10,18,99,32,9,7,2,3};
		int temp = 0;
		for(int i=0;i<s.length-1;i++){
			if(s[i+1]<s[i]){
				temp = s[i+1];
				
				int j = i;
				do{
					s[j+1]= s[j];
					j--;
				}while(j>=0&&temp<s[j]);
				s[j+1] = temp;
			}
		}
		System.out.println("insert sort");
		for(int i=0;i<s.length;i++){
			System.out.println(s[i]);
		}

 降序排列:

	int[] s = {20,10,18,99,32,9,7,2,3};
		int temp = 0;
		for(int i=1;i<s.length;i++){
			
			if(s[i]>s[i-1]){
				//如果第i个值小于
				temp = s[i];
				int j = i-1;
				do{
					s[j+1] = s[j];
					j--;
				}while(j>=0&&temp>s[j]);
				s[j+1] = temp;
			}
		}
		System.out.println("insert sort");
		for(int i=0;i<s.length;i++){
			System.out.println(s[i]);
		}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics