天天看點

7.7 學java 第三天之數組常見問題1.1數組中求最值

1.1數組中求最值

1.1.1最小值

public class Demo1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
       int a[]= {100,20,50,88,99,1};
       int n=a[0];
       for (int i = 1; i < a.length; i++) {
		n=n<a[i]?n:a[i];
		
	}
       System.out.println(n);
	}

}
           

1.1.2最大值

public class Demo1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
       int a[]= {100,20,50,88,99,1};
       int n=a[0];
       for (int i = 1; i < a.length; i++) {
		n=n>a[i]?n:a[i];
		
	}
       System.out.println(n);
	}

}
           

1.2冒泡排序

原理: 比較相鄰的元素。如果第一個比第二個大,就交換他們兩個。 - 對每一對相鄰元素做同樣的工作,從開始第一對到結尾的最後一對。在這一點,最後的元素應該會是最大的 數。 - 針對所有的元素重複以上的步驟,除了最後一個。 - 持續每次對越來越少的元素重複上面的步驟,直到沒有任何一對數字需要比較。

名字由來: 是因為最小(或最大)的元素會經由交換慢慢“浮”到數列的頂端(降序或升序),就如同水中的氣泡最終會上浮到 頂端一樣,故名“冒泡排序”。

升序排列的口訣:

N個數字來排隊

兩兩相比小靠前,

外層循環length-1

内層循環length-i-1

降序排序的口訣:

N個數字來排隊

兩兩相比大靠前

外層循環length-1

内層循環length-i-1

例如:升序

public class Demo2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
         int [] a=  {100,20,50,88,99,1};
         int temp=a[0];
         for(int i=0;i<a.length-1;i++) {
        	 for (int j = 0; j < a.length-i-1; j++) {
				if(a[j]>a[j+1]) {
					temp=a[j];
					a[j]=a[j+1];
					a[j+1]=temp;
				}
			}
        	 
			}for (int j = 0; j < a.length; j++) {
				System.out.println(a[j]);
         }
	}

}
           

1.3二分法

概述:

 二分查找也稱折半查找(Binary Search),它是一種效率較高的查找方法。但是,二分查找要求數組資料必須采用順 序存儲結構有序排列。

原理:

首先,假設數組中元素是按升序排列,将數組中間位置的資料與查找資料比較,如果兩者相等,則查找成功;否則利用 中間位置記錄将數組分成前、後兩個子數組,如果中間位置資料大于查找資料,則進一步查找前子數組,否則進一步查 找後子數組。 重複以上過程,直到找到滿足條件的資料,則表示查找成功, 直到子數組不存在為止,表示查找不成功。

例如:

public class Demo5 {

	/**
	 * 二分查找(折半查找)
	 */
	public static void main(String[] args) {
		int[] nums = {10,20,30,40,50,60,70,80,90};
		
		//要查找的資料
		int num = 20;
		
		//關鍵的三個變量:
		//1.	最小範圍下标
		int minIndex = 0;
		//2.	最大範圍下标
		int maxIndex = nums.length-1;
		//3.	中間資料下标
		int centerIndex = (minIndex+maxIndex)/2;
		while(true) {
			System.out.println("循環了一次");
			if(nums[centerIndex]>num) {
				//中間資料較大
				maxIndex = centerIndex-1;
			}else if(nums[centerIndex]<num) {
				//中間資料較小
				minIndex = centerIndex+1;
			}else {
				//找到了資料  資料位置:centerIndex
				break;
			}
			
			if(minIndex > maxIndex) {
				centerIndex = -1;
				break;
			}
			//當邊界發生變化, 需要更新中間下标
			centerIndex = (minIndex+maxIndex)/2;
		}
		
		System.out.println("位置:"+centerIndex);
		
	}
}