选择排序
public class Selection
{
public static int[] selectionSort(int[] array){
if (array.length == 0)
return array;
for(int i = 0; i < array.length; i++){
int minIndex = i;
for(int j = i; j < array.length; j++){
if(array[j] < array[i])
minIndex = j;
}
int temp = array[minIndex];
array[minIndex] == array[i];
array[i] = temp; //互换就对了
}
return array;
}
}
插入排序
public class Insert
{
public static int[] insertionSort(int[] array){
if (array.length == 0)
return array;
int current;
for(int i = 0; i < array.length; i++){
current = array[i + 1];
int preIndex = i;
while(preIndex >= 0 && current < array[preIndex]) {
array[preIndex + 1] = array[preIndex];
preIndex--; **//从后往前,也是可以。**
}
array[preIndex + 1] = current;
}
return array;
}
}
希尔排序
public static int[] ShellSort(int[] array) {
int len = array.length;
int temp, gap = len / 2;
while (gap > 0) {
for (int i = gap; i < len; i++) {
temp = array[i];
int preIndex = i - gap;
while (preIndex >= 0 && array[preIndex] > temp) {
array[preIndex + gap] = array[preIndex];
preIndex -= gap;
}
array[preIndex + gap] = temp;
}
gap /= 2;
}
return array;
}
public class ShellSort {
public void shellSort(int[] array, int n) {
int i, j, gap;
int temp;
for (gap = n / 2; gap > 0; gap /= 2) {// 计算gap大小
for (i = gap; i < n; i++) {// 将数据进行分组
for (j = i - gap; j >= 0 && array[j] > array[j + gap]; j -= gap) {// 对每组数据进行插入排序
temp = array[j];
array[j] = array[j + gap];
array[j + gap] = temp;
}
// 打印每趟排序结果
for (int m = 0; m <= array.length - 1; m++) {
System.out.print(array[m] + "\t");
}
System.out.println();
}
}
}
归并排序
public static int[] sort(int[] nums, int low, int high){
int mid = (low + high) / 2;
if(low < high){
sort(nums, low, mid);
sort(nums, mid+1, high);
merge(nums, low, mid, high);
}
return nums;
}
public static void merge(int[] nums, int low, int mid, int high){
int[] temp = new int[high - low + 1];
int i = low;
int j = mid + 1;
int k = 0;
while(i <= mid && j <= high){
if(nums[i] < nums[j]){
temp[k++] = nums[i++];
} else{
temp[k++] = nums[j++];
}
}
while(i <= mid){
temp[k++] = nums[i++];
}
while(j <= high){
temp[k++] = nums[j++];
}
for(int k2 = 0; k2 < temp.length; k2++){
nums[k2 + low] = temp[k2];
}
}
快速
public void quickSort(int R[], int low, int high){
int temp;
int i = low;
int j = high;
if(low < high){
temp = R[low];
while(i < j){
while( i < j && R[j] >= temp) --j;
if(i < j){
R[i] = R[j];
++i;
}
while( i < j && R[i] < temp) ++i;
if(i < j){
R[j] = R[i];
--j;
}
}
R[i] = temp;
quickSort(R, low, i-1);
quickSort(R, i+1, high);
}
}
网友评论