public class mergeSort {
public static void main(String []args){
int []arr = {10,9,8,7,6,5,4,3,2,1};
sort(arr);
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
public static void sort(int []arr){
int []temp = new int[arr.length];//在排序前,先建好一个长度等于原数组长度的临时数组,避免递归中频繁开辟空间
sort(arr,0,arr.length-1,temp);
}
public static 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);//将两个有序子数组合并操作
}
}
public static 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 class quickSort {
public static void println(int[] num){
for(int i=0;i<num.length;i++){
System.out.println(num[i]);
}
}
//快速排序
public static void quick_sort(int s[], int l, int r) {
if (l < r) {
int i = l, j = r, x = s[l];
while (i < j) {
while(i < j && s[j] >= x) {
// 从右向左找第一个小于x的数
j--;
}
if(i < j){
s[i++] = s[j];
}
while(i < j && s[i] < x){
// 从左向右找第一个大于等于x的数
i++;
}
if(i < j){
s[j--] = s[i];
}
}
s[i] = x;
quick_sort(s, l, i - 1); // 递归调用
quick_sort(s, i + 1, r);
}
}
public static void main(String[] args){
int[] num={10,9,8,7,6,5,4,3,2,1};
quick_sort(num,0,9);
println(num);
}
}
堆排序
public class heapSort {
static int len;
public static void swap(int[] num,int left,int right){
int tmp=num[left];
num[left]=num[right];
num[right]=tmp;
}
public static int[] heapSort(int[] num){
len=num.length;
if(len<1){
return num;
}
//构建一个最大堆
buildMaxHeap(num);
//循环将首位与末末位交换然后再重新调整最大堆
while(len>0){
swap(num,0,len-1);
len--;
adjustHeap(num,0);
}
return num;
}
public static void buildMaxHeap(int[] num){
for(int i=(len/2-1);i>=0;i--){
adjustHeap(num,i);
}
}
public static void adjustHeap(int[] num,int i){
int maxIndex=i;
//如果有左子树,且左子树大于父节点,则将最大值真指向左子树
if(i*2+1<len&&num[i*2]>num[maxIndex]){
maxIndex=i*2;
}
//如果有右子树且右子树大于父节点,则将最大指针指向右子树
if(i*2+1<len&&num[i*2+1]>num[maxIndex]){
maxIndex=i*2+1;
}
if(maxIndex!=i){
swap(num,maxIndex,i);
adjustHeap(num,maxIndex);
}
}
public static void main(String[] args){
int[] num={10,9,8,7,6,5,4,3,2,111};
heapSort(num);
for(int i=0;i< num.length;i++){
System.out.println(num[i]);
}
}
}