Summary
1.Array memory space complexity:
Quick sort :O(1)
Merge sort: O(n)
Heap sort: O(n)
2.Quick Sort VS Merge Sort
Quick sort:先全局有序再局部有序
Merge sort: 先局部有序再全局有序
1>都是Divided conquer算法
2> Space complexity: O(1) VS O(n)
3>Quick sort是不稳定排序,merge sort 是稳定排序
4> Quick sort 平均时间为O(nlogn), Merge sort最好最坏为O(nlogn)
Quick Sort:
/* This function takes mid element as pivot, places the pivot element at its
correct position in sorted array, and places all smaller (smaller than pivot)
to left of pivot and all greater elements to right of pivot */
public static int partition(int[] arr,int left,int right)
{
int i=left;
int j=right;
int temp;
int pivot= arr[(left+right)/2];
while(i<=j)
{
while(arr[i]<pivot)
i++;
while(arr[j]>pivot)
j--;
if(i<=j)
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++;
j--;
}
}
return i;
}
public static void quickSort(int[] arr,int left,int right)
{
int index=partition(arr,left,right);
if(left<index-1)
{
quickSort(arr,left,index-1);
}
if(right>index)
{
quickSort(arr,index,right);
}
}partition 函数模板:
Merge Sort:
Last updated
Was this helpful?