java新手笔记7 找最小、最大、排序

1.最小数

// 1.0
public class SortDemo1 {
  
   public static void main(String[] args) {

	   int[] a = {2,5,4,6,8,1,3,9};
       int min = a[0];//最小数
	   int k = 0;
	   int temp;
	   for(int i = 0; i < a.length; i++ ) {
             System.out.print( a[i] + "	");
	  }
	   //最小数

       for(int j = 0; j < a.length; j++ ) {
             if( min > a[j]) {
                 k = j;
				 min = a[j];
			 }

	   }

	   temp = a[0];
	   a[0] = a[k];
	   a[k] = temp;

	   


      System.out.println("
最小值 : " + min);
	  System.out.println("索引 : " + k);
	  System.out.println("a[5] : " + a[k]);
	  System.out.println("a[0] : " + a[0]);

	  for(int i = 0; i < a.length; i++ ) {
             System.out.print( a[i] + "	");

	  }

    
    }

}

 2.数组最小数

// 1.1
public class SortDemo2 {
  
   public static void main(String[] args) {

	   int[] a = {0,2,5,2,5,0};
       int min = a[0];//最小数
	   int k = 0;
	   int temp;
	   System.out.print( "数组数据 : ");
	   for(int i = 0; i < a.length; i++ ) {
             System.out.print( a[i] + "	");
	  }
	   //最小数
     
	 for(int i = 0; i < a.length - 1; i++ ) {
		 k = i; //默认当前的最小值
      //从剩下的元素找最小值
       for(int j = i; j < a.length; j++ ) {//内层的起始值
             if( a[k] > a[j]) {//a[k]值是默认最小值
                 k = j;				
			                          }             
	                                          }
       
	   //数据交换  如果当前值最小 不进行交换
	 if(k != i) {
		   temp = a[i];//  0   0  k == i
		   a[i] = a[k];
		  // System.out.print(".temp = " + temp +  "  :  a[k] = " + a[k]  +  "  : a[i] = " + a[i]);
		   a[k] = temp;
	             }
	   /*
	   System.out.print( "
");
       for(int x = 0; x < a.length; x++ ) {
             System.out.print( a[x] + "	");
	  }
	  */
	 }
    System.out.print( "
");
	   System.out.print( "数组数据 : ");
	  for(int i = 0; i < a.length; i++ ) {
             System.out.print( a[i] + "	");

	  }

    
    }

}

 3.排序,大数后置

// 1.1
public class SortDemo3 {
  
   public static void main(String[] args) {

	   int[] a = {7,5,6,3,2,1,4,9,8,6};
      
	   int temp;
	   System.out.print( "数组数据 : ");
	   for(int i = 0; i < a.length; i++ ) {
             System.out.print( a[i] + "	");
	                                                     }
	   //相邻的元素比较  8  
     for(int i = 0; i < a.length - 1; i++ ) {
	   //每次找最大数放在最后
       for(int j = 0; j < a.length - 1 - i; j++ ) { // 0 - 3
                if( a[j] > a[j+1] ) { //交换
					temp = a[j];
					a[j] = a[j+1];
					a[j+1] = temp; 
		      }
	                                                }
       
	                                         }
                        System.out.print( "
");
	   System.out.print( "数组数据 : ");
	  for(int i = 0; i < a.length; i++ ) {
                      System.out.print( a[i] + "	");

	  }

    
    }

}
原文地址:https://www.cnblogs.com/feilongblog/p/4656776.html