1.插入排序-直接插入排序
public class Test {
public static void main(String[] args) {
int[] array = {23,34,45,234,23,34,46,732,7,4,24,45};
insertSort(array);
}
public static void insertSort(int[] a){
for(int i=1; i<a.length; i++){
if (a[i] < a[i-1]){
int j = i-1;
int flag = a[i];
while(flag < a[j]){
a[j+1] = a[j];
j--;
if(j == -1){
break;
}
}
a[j+1] = flag;
}
print(a);
}
}
private static void print(int[] a) {
for (int i : a) {
System.out.print(i+" ");
}
System.out.println();
}
}
运行结果:
23 34 45 234 23 34 46 732 7 4 24 45
23 34 45 234 23 34 46 732 7 4 24 45
23 34 45 234 23 34 46 732 7 4 24 45
23 23 34 45 234 34 46 732 7 4 24 45
23 23 34 34 45 234 46 732 7 4 24 45
23 23 34 34 45 46 234 732 7 4 24 45
23 23 34 34 45 46 234 732 7 4 24 45
7 23 23 34 34 45 46 234 732 4 24 45
4 7 23 23 34 34 45 46 234 732 24 45
4 7 23 23 24 34 34 45 46 234 732 45
4 7 23 23 24 34 34 45 45 46 234 732
2.插入排序-希尔排序
public class ShellTest {
public static void main(String[] args) {
int[] array = {23,34,45,234,23,34,46,732,7,4,24,45};
shellSort(array);
}
private static void shellSort(int[] a) {
int half = a.length/2;
while(half>=1){
shellsort(a,half);
half=half/2;
}
}
private static void shellsort(int[] a, int half) {
for(int i= half; i<a.length; ++i){
if(a[i] < a[i-half]){ //若第i个元素大于i-1元素,直接插入。小于的话,移动有序表后插入
int j = i-half;
int x = a[i]; //复制为哨兵,即存储待排序元素
a[i] = a[i-half]; //首先后移一个元素
while(x < a[j]){ //查找在有序表的插入位置
a[j+half] = a[j];
j -= half; //元素后移
if(j < -1){
break;
}
}
a[j+half] = x; //插入到正确位置
}
print(a);
}
}
private static void print(int[] a) {
for (int i : a) {
System.out.print(i+" ");
}
System.out.println();
}
}
3.选择排序-简单选择排序
/**
* 选择排序简单选择排序
*
*
*
*/
public class SimpleSelectionSort {
public static void main(String[] args) {
int[] array = {23,34,45,234,23,34,46,732,7,4,24,45};
simpleSelectionSort(array);
}
/**
* 1. 第一次在n中先找出最小的值,与第一位交换
* 2. 第二次在2~n中找出最小的值,与第二位交换
* 3. 以此类推......直到交换到n-1位置时结束
* @param a
*/
private static void simpleSelectionSort(int[] a) {
for(int i=0; i<a.length-1; i++){
int min = a[i];
int flag = i;
for( int j = i; j<a.length-1; j++){
if(a[j+1] < min){
min = a[j+1];
flag = j+1;
}
}
a[flag] = a[i];
a[i] = min;
print(a);
}
}
private static void print(int[] a) {
for (int i : a) {
System.out.print(i+" ");
}
System.out.println();
}
}
运行结果:
4 34 45 234 23 34 46 732 7 23 24 45
4 7 45 234 23 34 46 732 34 23 24 45
4 7 23 234 45 34 46 732 34 23 24 45
4 7 23 23 45 34 46 732 34 234 24 45
4 7 23 23 24 34 46 732 34 234 45 45
4 7 23 23 24 34 46 732 34 234 45 45
4 7 23 23 24 34 34 732 46 234 45 45
4 7 23 23 24 34 34 45 46 234 732 45
4 7 23 23 24 34 34 45 45 234 732 46
4 7 23 23 24 34 34 45 45 46 732 234
4 7 23 23 24 34 34 45 45 46 234 732