希尔排序(Shell Sort)又称为缩小增量排序(diminishing increment sort)
该算法是一种泛化的插入排序。
希尔排序也称为n间距(n-gap)插入排序。希尔排序分多路并使用不同的间距来比较元素,通过逐步减少间距,最终以1为间距进行排序。
public static void shellSort(int[] array) {
int length = array.length;
int temp;
int i, j;
for (int gap = length / 2; gap > 0; gap /= 2) {
for (i = gap; i < length; i++) {
temp = array[i];
j = i;
while ((j >= gap) && (array[j - gap] > temp)) {
array[j] = array[j - gap];
j -= gap;
}
array[j] = temp;
}
}
}
归并排序(Merge Sort)
参考:http://blog.csdn.net/yinjiabin/article/details/8265827/
public static void mergeSort(int[] array, int left, int right) {
if (right > left) {
int mid = (left + right) / 2;
mergeSort(array, left, mid);
mergeSort(array, mid + 1, right);
merge(array, left, mid + 1, right);
}
}
public static void merge(int[] array, int left, int mid, int right) {
int left_end = mid - 1;
int size = right - left + 1;
int[] temp = new int[array.length];
int temp_pos = left;
while ((left <= left_end) && (mid <= right)) {
if (array[left] <= array[mid]) {
temp[temp_pos] = array[left];
temp_pos++;
left++;
} else {
temp[temp_pos] = array[mid];
temp_pos++;
mid++;
}
}
while (left <= left_end) {
temp[temp_pos] = array[left];
temp_pos++;
left++;
}
while (mid <= right) {
temp[temp_pos] = array[mid];
temp_pos++;
mid++;
}
for (int i = 0; i < size; i++) {
array[right] = temp[right];
right--;
}
}
快速排序(Quick Sort)也称为分区交换排序
思路:
1.如果数组中只有一个元素或者没有数据需要排序则直接返回
2.选择数组中的一个元素作为中心点(pivot),通常选择数组最右侧的元素
3.把数组分为两部分,一部分是元素大于中心点,一部分是元素小于中心点
4.递归处理两部分数组
public static void quickSort(int[] array, int low, int high) {
if (high > low) {
int pivot = partition(array, low, high);
quickSort(array, low, pivot - 1);
quickSort(array, pivot + 1, high);
}
}
public static int partition(int[] array, int low, int high) {
int pivot_item = array[low];
int left = low;
int right = high;
while (left < right) {
while (left <= high && (array[left] <= pivot_item)) {
left++;
}
while (right >= low && (array[right] > pivot_item)) {
right--;
}
if (left < right) {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}
}
array[low] = array[right];
array[right] = pivot_item;
return right;
}