排序算法---2

来源:互联网 发布:网络发帖犯法吗 编辑:程序博客网 时间:2024/05/29 12:48

排序算法---2

1、归并排序

时间复杂度为O(N*logN) 空间复杂度 O(N)


public void mergeSort(int[] A, int n) {Sort(A,0,A.length-1);    }public void Sort(int[] a, int left, int right) {if(left<right){int mid=(left+right)/2;Sort(a,left,mid);Sort(a,mid+1,right);Merge(a,left,mid,right);}}public void Merge(int[] a, int left, int mid, int right) {int[]temp =new int[a.length];int i=left;int j=mid+1;int k=0;while (i<=mid&&j<=right) {if(a[i]<=a[j]){temp[k++]=a[i++];}else{temp[k++]=a[j++];}}while(i<=mid){temp[k++]=a[i++];}while(j<=right){temp[k++]=a[j++];}for(i=0;i<k;i++){a[left+i]=temp[i];}}

2、快速排序

时间复杂度为O(N*logN) 空间复杂度 O(logN)
public int[] data;public int partition(int[] data,int low,int high){int key=data[low];while(low<high){while(low<high&&data[high]>=key){high--;}data[low]=data[high];while(low<high&&data[low]<=key){low++;}data[high]=data[low];}data[low]=key;return low;}public int[] sort(int low,int high) {if(low<high){int result= partition(data ,low,high);sort(low,result-1);sort(result+1,high);}return data;}

3、堆排序

时间复杂度为O(N*logN) 空间复杂度 O(1)

public class HeapSort {    public int[] heapSort(int[] A, int n) {        for(int i=n/2; i>=0; i--){            heapAdjust(A,i,n);        }                 for(int i=n-1;i>0;i--){            swap(A,0,i);            heapAdjust(A,0,i);        }        return A;    }         void heapAdjust(int[] A,int index,int length){        int childLeft;        int temp = A[index];        for( ;index*2+1 < length;index = childLeft){            childLeft = index*2+1;            if(childLeft !=length-1 && A[childLeft] < A[childLeft+1]){                 childLeft++;            }            if(temp > A[childLeft]){                break;                             }                           else {                A[index] = A[childLeft];                index = childLeft;            }                  }         A[index] = temp;             }         static void  swap(int[] A,int m,int n){        int temp = A[m];        A[m] = A[n];        A[n] = temp;    }


4、希尔排序

时间复杂度为O(N^1.25)
是插入排序的改良
int feet = arr.length / 2;        int index = 0;        while (feet > 0) {            for (int i = feet; i < arr.length; i++) {                index = i;                while (index >= feet) {                    if (arr[index - feet] > arr[index]) {                        swap(arr, index - feet, index);                        index -= feet;                    } else {                        break;                    }                }            }            feet /= 2;        }    }     public static void swap(int[] arr, int index1, int index2) {        int tmp = arr[index1];        arr[index1] = arr[index2];        arr[index2] = tmp;    }



0 0
原创粉丝点击