插入排序
import java.util.*;
public class InsertSort
{
public static int[] sort(int[] x)
{
int N = x.length;
int[] a = new int[N];
for (int i = 0; i < N; i++)
a[i] = x[i];
for (int i = 1; i < N; i++)
for (int j = i; j >= 1 && less(a, j, j-1); j--)
swap(a, j, j-1);
return a;
}
private static boolean less(int[] x, int i, int j)
{
return x[i] < x[j];
}
private static void swap(int[] x, int i, int j)
{
int t = x[i];
x[i] = x[j];
x[j] = t;
}
public static void main(String[] args)
{
Random random = new Random();
int[] a = new int[20];
for (int i = 0; i < 20; i++)
a[i] = random.nextInt(100);
StdOut.println(Arrays.toString(a));
int[] r = sort(a);
System.out.println(Arrays.toString(r));
}
}
/*
[42, 63, 92, 76, 10, 99, 75, 78, 0, 8, 84, 52, 54, 16, 97, 30, 39, 76, 50, 9]
[0, 8, 9, 10, 16, 30, 39, 42, 50, 52, 54, 63, 75, 76, 76, 78, 84, 92, 97, 99]
*/
import java.util.*;
public class ShellSort
{
public static int[] sort(int[] x)
{
int N = x.length;
int[] a = new int[N];
for (int i = 0; i < N; i++)
a[i] = x[i];
int step = 1;
while (step < N/3)
{
step = step * 3 + 1; // 1,4,13,40,121...
}
while (step >= 1)
{
for (int i = step; i < N; i++)
{
for (int j = i; j >= step && less(a, j, j - step); j -= step)
swap(a, j, j-step);
}
step /= 3;
}
return a;
}
private static boolean less(int[] x, int i, int j)
{
return x[i] < x[j];
}
private static void swap(int[] x, int i, int j)
{
int t = x[i];
x[i] = x[j];
x[j] = t;
}
public static void main(String[] args)
{
Random random = new Random();
int[] a = new int[20];
for (int i = 0; i < 20; i++)
a[i] = random.nextInt(100);
StdOut.println(Arrays.toString(a));
int[] r = sort(a);
System.out.println(Arrays.toString(r));
}
}
/*
[79, 43, 40, 5, 9, 80, 4, 77, 97, 2, 14, 97, 55, 77, 20, 90, 41, 64, 82, 94]
[2, 4, 5, 9, 14, 20, 40, 41, 43, 55, 64, 77, 77, 79, 80, 82, 90, 94, 97, 97]
*/