一道??嫉膉avaSE面試題
就這道題我也想些想法,當(dāng)時(shí)他們和我說完,我在想用什么方法可以實(shí)現(xiàn)。畢竟現(xiàn)在javaSE都忘的差不多了,現(xiàn)在主要學(xué)的還是javaEE方面。年前學(xué)習(xí)JSP和SERVLET一片的知識(shí),到了年后主要學(xué)習(xí)三大框架、ajax、jquery和XML等。不過當(dāng)時(shí)出現(xiàn)腦中的算法只有:java.util包中定義的Arrays類和冒泡法。
下面就拿上面方說的那兩種方法具體說說。
在JDK的java.util包中定義的Arrays類提供了多種數(shù)據(jù)操作方法,實(shí)現(xiàn)了對(duì)數(shù)組元素的排序、填充、轉(zhuǎn)換、增強(qiáng)檢索和深度比較等功能,所以的這些方法都是static的,下面介紹對(duì)數(shù)組元素進(jìn)行排序的方法。數(shù)組元素的排序通常是指一維數(shù)值型數(shù)組元素按升序排序,偶爾也會(huì)涉及一維String數(shù)組排序,一般來說,多維和其他引用類型的元素?cái)?shù)組排序使用意義不大。
Arrays類中的sort()的格式:
public static void sort(
案例1:
JDK的java.util包中定義的Arrays類提供了排序方法
一維數(shù)組排序:
Java代碼
- package cn.z_xiaofei168.sort;
- import java.util.Arrays;
- public class TestArraySort {
- /**
- * @author z_xiaofei168
- */
- public static void main(String[] args) {
- int[] arr = { -1, -3, 5, 7, 9, 2, 4, 6, 8, 10 };
- System.out.print("整數(shù)排序前:");
- displayIntArr(arr);
- Arrays.sort(arr);
- System.out.print("整數(shù)排序后:");
- displayIntArr(arr);
- String[] name = {"Tom","Kitty","James","z_xiaofei168","DXL_xiaoli","Zhang_Di"};
- System.out.print("字符串排序前:");
- displayStringArr(name);
- Arrays.sort(name);
- System.out.print("字符串排序后:");
- displayStringArr(name);
- }
- /** 整數(shù)排序方法 */
- public static void displayIntArr(int[] arr) {
- for (int i : arr) {
- System.out.print(i + "\t");
- }
- System.out.println();
- }
- /** 字符串排序方法 */
- public static void displayStringArr(String[] arr) {
- for (String s : arr) {
- System.out.print(s + "\t");
- }
- System.out.println();
- }
- }
運(yùn)行結(jié)果如下圖所示:
案例2:冒泡法
Java代碼
- package cn.z_xiaofei168.sort;
- public class TestMaopao {
- /**
- * @author z_xiaofei168
- */
- public static void main(String[] args) {
- int[] arr = { -1, -3, 5, 7, 9, 2, 4, 6, 8, 10 };
- System.out.print("整數(shù)排序前:");
- for(int ar : arr){
- System.out.print(ar+"\t");
- }
- System.out.println();
- displayIntArr(arr);
- System.out.print("整數(shù)排序后:");
- for(int a : arr){
- System.out.print(a+"\t");
- }
- }
- /** 冒泡排序方法 */
- public static void displayIntArr(int[] arr) {
- for (int i=arr.length-1;i>0;i--) {
- for (int j = 0; j < i; j++) {
- if(arr[j]>arr[j+1]){
- int temp;
- temp = arr[j];
- arr[j] = arr[j+1];
- arr[j+1] = temp;
- }
- }
- }
- }
- }
運(yùn)行結(jié)果如下圖所示:
大家還有什么方法可以實(shí)現(xiàn)這個(gè)功能,請(qǐng)大家給我留言。以至于我們共同學(xué)習(xí)、共同進(jìn)步。
【編輯推薦】