本帖最後由 tonyh 於 2020-2-4 14:53 編輯
假設有一陣列其內容為:
int n[]={34,65,7,-3,6546,-564,0,-11,90,123};
試運用 Arrays 類別中的 sort() 函式, 對該陣列排序.
- import java.util.Arrays;
- public class Ch42
- {
- public static void main(String args[])
- {
- int n[]={34,65,7,-3,6546,-564,0,-11,90,123};
- System.out.println("排序前:");
- for(int i=0; i<n.length; i++)
- System.out.print(n[i]+" ");
- System.out.println();
- Arrays.sort(n);
- System.out.println("排序後:");
- for(int i=0; i<n.length; i++)
- System.out.print(n[i]+" ");
- }
- }
複製代碼- import java.util.Arrays;
- public class Ch30 {
- public static void main(String args[]) {
- int n[]={34,65,7,-3,6546,-564,0,-11,90,123};
- System.out.println("排序前: ");
- for(int i=0; i<n.length; i++)
- System.out.print(n[i]+" ");
- Arrays.sort(n);
- System.out.println("\n排序後(遞增): ");
- for(int i=0; i<n.length; i++)
- System.out.print(n[i]+" ");
- System.out.println("\n排序後(遞減): ");
- for(int i=n.length-1; i>=0; i--)
- System.out.print(n[i]+" ");
- }
- }
複製代碼 |