經過幾家的面試,發現每次筆試都有一道排序的題目,所以梳理一下,防止在面試中卡殼。
1、使用JAVA實現一個冒泡排序:
源碼:
public static void main(String[] args) {
int [] a = {4,1,18,6,5,9};
int [] c = bubbleSort(a);
System.out.print("冒泡排序結果: ");
for (int i = 0; i < c.length; i++) {
System.out.print(c[i]+" ");
}
}
public static int [] bubbleSort(int [] a){
int temp = 0;
for(int i=1;i<a.length;i++){
for(int j=0;j<a.length-i;j++){
//一次比較兩個元素,如果前者大於後者,就將他們進行交換。
if (a[j] > a[j+1]) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
return a;
}
代碼分析:見《JAVA之冒泡排序》
2、使用JAVA實現一個選擇排序:
源碼:
public static void main(String[] args) {
int [] a = {7,4,9,13,1,6};
int [] c = chooseSort(a);
for (int i = 0; i < c.length; i++) {
System.out.print(c[i]+ " ");
}
}
/**
* 選擇排序:
* 從數列中第一位開始,遍歷之後的所有,選擇出最小的一個放到第一位。
* 接下來從第二位開始,找到數組中第二個小數,放到第二個位置,以此類推。
* @param a
* @return
*/
public static int [] chooseSort(int [] a){
//定義最小數據的下表,默認是第一個
int minIndex = 0;
for (int i = 0; i < a.length-1; i++) {
minIndex = i;
for (int j = i+1; j < a.length; j++) {
if(a[minIndex]>a[j]){
minIndex = j;
}
}
//找到最小值的角標,進行交換
if (minIndex != i){
int temp = a[i];
a[i] = a[minIndex];
a[minIndex] = temp;
}
}
return a;
}
代碼分析:見《JAVA之選擇排序》
3、使用JAVA實現一個插入排序:
源碼:
public static void main(String[] args) {
int [] a = {7,4,9,13,1,6};
int [] c = insertSort(a);
for (int i = 0; i < c.length; i++) {
System.out.print(c[i]+" ");
}
}
private static int[] insertSort(int[] a) {
int inserNode;
int j;
for (int i = 1; i < a.length; i++) {
inserNode = a[i];
j = i-1;
while (j>=0 && a[j]>inserNode){
a[j+1] = a[j];
j--;
}
a[j+1] = inserNode;
}
return a;
}
代碼分析:見《JAVA之插入排序》
總結:鞏固基礎,勇攀高峯!