前言
首先是背景,剛放假回家比較閑,就把以前寫了一些算法題的一個項目拿出來繼續寫,想把其中的插入排序修改成支持升序和降序的,然后就出現了這個坑,具體是這樣的:
先把插入排序的代碼擺出來吧。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
/** * 插入排序 * @param arr 輸入數組 * @param order 順序 1為升序 0為降序 */ static void insertionsort( int arr[], int order){ for ( int i = 1 ; i < arr.length; i++) { int get = arr[i]; int j = i - 1 ; while (j >= 0 && (order == 1 ) ? (arr[j] > get):(arr[j] < get)) { arr[j + 1 ] = arr[j]; j--; } arr[j + 1 ] = get; } } |
main函數是這樣調用的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public static void main(string[] args){ int [] arr = { 8 , 96 , 23 , 5 , 6 , 43 }; for ( int a :arr){ system.out.print(a + "," ); } system.out.println(); insertionsort(arr, 1 ); for ( int a :arr){ system.out.print(a + "," ); } system.out.println(); insertionsort(arr, 0 ); for ( int a :arr){ system.out.print(a + "," ); } } |
運行后日志是這樣的:
8,96,23,5,6,43,
exception in thread "main" java.lang.arrayindexoutofboundsexception: -1
異常的意思是說數組越界了,且問題出在這一行
1
|
while (j >= 0 && (order == 1 ) ? (arr[j] > get):(arr[j] < get)) |
代碼中j每次循環都會減1直到這兩個條件都不滿足為止,debug后發現是j=-1的時候出現的異常,但問題是j=-1的時候,不會去使用數組啊,因為眾所周知&&屬于短路操作,即如果第一個操作數能夠決定結果,那么就不會再對第二個操作數求值,也就是說j=-1的時候后面的表達式是不會計算的啊,但這里進行計算了,從數組中取值了,所以出現了這個異常。
我也隨便寫了一些代碼測試了一下這種情況:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
/** * 對比兩個輸入參數的大小 * @param a 輸入參數1 * @param b 輸入參數2 * @return boolean 如果a > b 返回true,反之返回false */ static boolean compare( int a, int b){ system.out.println(a + ">" + b + "?" ); system.out.println(a > b); return a > b; } public static void main(string[] args){ int a = 1 ; int b = 2 ; int c = 3 ; boolean result = compare(a ,a) && (a == 1 ) ? (compare(b,b)):(compare(c,c)); system.out.println(); result = compare(b ,b) && compare(c ,c); } |
這里有一個對比大小的函數,這個函數會打出日志來讓我們清晰的看到&&前后的表達式運行了沒有,main函數中有兩個&&表達式,
第一個&&表達式中b是一個?表達式,第二的個&&表達式的b就是一個compare函數,日志結果是:
1>1?
false
3>3?
false
2>2?
false
從日志結果我們可以清晰的看到,當b是?表達式的時候,a不成立的時候下b依舊運行了,而b不是?表達式的時候,a是false的情況下b是不會執行的。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://www.cnblogs.com/xxbbtt/p/10346564.html