归并排序 抄的
import java.util.Arrays;
public class MergeSort {
int[] array;
public MergeSort(int[] array) {
this.array = array;
}
public void sort() {
int[] temp = new int[array.length];//在排序前,先建好一个长度等于原数组长度的临时数组,避免递归中频繁开辟空间
sort(array, 0, array.length - 1, temp);
}
private void sort(int[] arr, int left, int right, int[] temp) {
if (left < right) {
int mid = (left + right) / 2;
sort(arr, left, mid, temp);//左边归并排序,使得左子序列有序
sort(arr, mid + 1, right, temp);//右边归并排序,使得右子序列有序
merge(arr, left, mid, right, temp);//将两个有序子数组合并操作
}
}
private void merge(int[] arr, int left, int mid, int right, int[] temp) {
int i = left;//左序列指针
int j = mid + 1;//右序列指针
int t = 0;//临时数组指针
while (i <= mid && j <= right) {
if (arr[i] < arr[j]) {
temp[t++] = arr[i++];
} else {
temp[t++] = arr[j++];
}
}
while (i <= mid) {//将左边剩余元素填充进temp中
temp[t++] = arr[i++];
}
while (j <= right) {//将右序列剩余元素填充进temp中
temp[t++] = arr[j++];
}
t = 0;
//将temp中的元素全部拷贝到原数组中
while (left <= right) {
arr[left++] = temp[t++];
}
}
public void print() {
int i = 0;
while (i < array.length) {
System.out.println(array[i++]);
}
}
public static void main(String[] args) {
int[] arr = {3,1,9,6,8,12, 4, 5, 65, 3, 2, 3, 5, 57, 2};
System.out.println(Arrays.toString(arr));
MergeSort mergeSort = new MergeSort(arr);
mergeSort.sort();
System.out.println(Arrays.toString(arr));
}
}
快速排序
public class FastSort {
int [] array;
public FastSort(int []arr){
this.array=arr;
}
public void sort() {
sort(array, 0, array.length-1);
}
public void sort(int[] array,int low,int high) {
if(low<high) {
int pivotloc=partition(array, low, high);
sort(array, low, pivotloc-1);
sort(array, pivotloc+1, high);
}
}
public int partition(int []array,int low,int high) {
// array[0]=array[low];
int key=array[low];
while(low<high) {
while(low<high&&array[high]>=key) {
high--;
}
array[low]=array[high];
while(low<high&&array[low]<=key) {
low++;
}
array[high]=array[low];
}
array[low]=key;
return low;
}
public static void main(String[] args) {
int[] arr = {3,1,9,6,8,12, 4, 5, 65, 3, 2, 3, 5, 57, 2};
FastSort fastSort = new FastSort(arr);
fastSort.sort();
System.out.println(Arrays.toString(arr));
}
}
桶排序--所有排序算法中最快、最简单的排序算法
public class BucketSort {
int []input;
int[]bucket;
public BucketSort(int range,int []input) {
this.input=input;
this.bucket=new int[range];
}
public void sort() {
for(int i=0;i<input.length;i++) {
bucket[input[i]]++;
}
for(int i=0;i<bucket.length;i++) {
while(bucket[i]>0) {
System.out.print(i+" ");
bucket[i]--;
}
}
}
public static void main(String[] args) {
int[]input = {4,3,2,1,8,5,9,7,6 };
BucketSort test = new BucketSort(10, input);
test.sort();
}
}