排序是算法的基础
目录
基础排序
选择排序
- 首先,找到数组中最小的那个元素
- 其次,将它和数组的第一个元素交换位置(如果第一个元素就是最小元素那么它就和自己交换)
- 再次,在剩下的元素中找到最小的元素,将它与数组的第二个元素交换位置。如此往复,直到将整个数组排序。这种方法叫做选择排序,因为它在不断地选择剩余元素之中的最小者。
插入排序
- 人们整理桥牌的方法是一张一张的来, 将每一张牌插入到其他已经有序的牌中的适当位置。
- 在计算机的实现中,为了给要插入的元素腾出空间,我们需要将其余所有元素在插入之前都向右移动一位。
希尔排序
- 希尔排序的思想是使数组中任意间隔为h的元素都是有序的。这样的数组被称为h有序数组。
- 换句话说,一个h有序数组就是h个互相独立的有序数组编制在一起组成的一个数组。在进行排序的时候,如果h很大,我们能够将元素移动到很远的地方,为了实现更小的h有序创造方便,用这种方式,对于任意以1结尾的h序列,我们都能够将数组排序,这就是希尔排序。
public class Sort {
public static void main(String[] args) {
int[] c = { 3, 2, 1, 6, 5, 7 };
print(c);
// selectionSort(c);
// insertSort(c);
shellSort(c);
}
static void selectionSort(int[] c) {
for (int i = 0; i < c.length; i++) {
int min = i;
for (int j = i + 1; j < c.length; j++) {
if (c[j] < c[min]) {
min = j;
}
}
int temp = c[i];
c[i] = c[min];
c[min] = temp;
}
print(c);
}
static void insertSort(int[] c) {
for (int i = 0; i < c.length; i++) {
int now = i;
for (int j = i - 1; j >= 0; j--) {
if (c[j] > c[now]) {
int temp = c[j];
c[j] = c[now];
c[now] = temp;
now = j;
}
}
}
print(c);
}
static void shellSort(int[] c) {
int step = 1;
while (step < c.length / 3) {
step = step * 3 + 1;
}
while (step >= 1) {
for (int i = 0; i < c.length; i++) {
int now = i;
for (int j = i - step; j >= 0; j = -step) {
if (c[j] > c[now]) {
int temp = c[j];
c[j] = c[now];
c[now] = temp;
now = j;
}
}
}
step =step-1;
}
print(c);
}
static void print(int[] c) {
for (int i : c) {
System.out.print(i + " ");
}
System.out.println();
}
}