最近在面試
定義數組如下
[java]
int[] array = new int[]{
int[] array = new int[]{
首先是插入排序
[java]
/**
* insert sort
* @param a
*/
private static void insertSort(int[] a){
System
for (int i =
int temp = a[i];
int j = i
while (j >=
a[j +
j
}
a[j +
System
printArray(a);
}
System
printArray(a);
}
/**
* insert sort
* @param a
*/
private static void insertSort(int[] a){
System
for (int i =
int temp = a[i];
int j = i
while (j >=
a[j +
j
}
a[j +
System
printArray(a);
}
System
printArray(a);
}
運行結果
插入排序過程
第
第
第
第
第
插入排序結果:
希爾排序實現
[java]
private static void shellInsertSort(int[] a
int i
for (i = start + dk; i < a
j = i
int temp = a[i];
while(j >=
a[j + dk] = a[j];
j
}
a[j + dk] = temp;
}
System
printArray(a);
}
private static void shellInsertSort(int[] a
int i
for (i = start + dk; i < a
j = i
int temp = a[i];
while(j >=
a[j + dk] = a[j];
j
}
a[j + dk] = temp;
}
System
printArray(a);
}
冒泡排序實現
[java]
/**
* bubble sort
* @param a
*/
private static void bubbleSort(int[] a){
System
for (int i =
for (int j =
if(a[j] > a[j +
int temp = a[j];
a[j] = a[j +
a[j +
}
}
System
printArray(a);
}
System
printArray(a);
}
/**
* bubble sort
* @param a
*/
private static void bubbleSort(int[] a){
System
for (int i =
for (int j =
if(a[j] > a[j +
int temp = a[j];
a[j] = a[j +
a[j +
}
}
System
printArray(a);
}
System
printArray(a);
}
運行結果
冒泡排序過程
第
第
第
第
第
第
冒泡排序結果
改進的冒泡排序算法
[java] view plaincopyprint?private static void bubbleSortBetter(int[] a){
System
boolean bool;
int i =
do{
bool = false;
for (int j =
if(a[j] > a[j +
int temp = a[j];
a[j] = a[j +
a[j +
bool = true;
}
}
i ++;
System
printArray(a);
}while(bool == true && i < a
System
printArray(a);
}
private static void bubbleSortBetter(int[] a){
System
boolean bool;
int i =
do{
bool = false;
for (int j =
if(a[j] > a[j +
int temp = a[j];
a[j] = a[j +
a[j +
bool = true;
}
}
i ++;
System
printArray(a);
}while(bool == true && i < a
System
printArray(a);
}
運行結果
改進的冒泡排序過程
第
第
第
改進的冒泡排序結果
與之前算法對比可見效果
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26844.html