void sort(int A[], int k)
冒泡 O(N2) O ( N 2 )
遍历k次数组,前者比后者大就换位置,使得每次遍历后,最大的数组往后移动至正确的位置。
void bobsort(int A[], int k){
for(int i=0; i<k; i++){
for(int j=0; j<k-i-1; j++){
if(A[j]>A[j+1])
swap(A[j], A[j+1]);
}
}
}
快排 O(NlogN) O ( N l o g N )
1)从数组中取一个为基准值(为中轴);
2)通过交换,它右边的数组都比它大,他左边的数组都比它小;
3)递归,结束条件为待排序序列只有0/1个元素。
void qsort(){
}
void partition(){
}
插入排序
希尔排序
归并排序
归并的思想是两两归并,然后四四归并,然后八八归并。
归并主要依赖于Merge操作:
1)申请空间用存放归并后的数组
2)设置两个指针,分别指向两个序列的开头
3)比较两个指针指向的值的大小,把小的值copy到临时数组,对应指针+1
4)如果一个序列的指针先走完,则把另一个序列的剩下元素全部copy至临时数组(这里可以直接copy回原数组)
5)copy临时数组的元素至原数组对应位置。
void Msort(int A[], int tempA[], int left, int right){
int center;
if(left < right){
center=(left + right) / 2;
Msort(A, tempA, left, center);
Msort(A, tempA, center+1, right);
merge(A, tempA, left, center, right);
}
}
void merge(int A[], int tempA[], int Lpos, int Rpos, int rightEnd){
int nElements = rightEnd - Lpos;
int temp = Lpos;
int leftEnd = Rpos - 1;
while(Lpos < leftEnd && Ppos < rightEnd){
if(A[Lpos] <= A[Rpos])
tempA[temp++] = A[Lpos++];
else
tempA[temp++] = A[Rpos++];
}
if(Lpos >= leftEnd)
while(Rpos < rightEnd) tempA[temp++] = A[Rpos++];
if(Rpos >= rightEnd)
while(Lpos < leftEnd) tempA[temp++] = A[Lpos++];
for(; i < nElements; i++, rightEnd--)
A[rightEnd] = tempA[rightEnd];
}
void MergeSort(int A[]){
int tempA[A.size()];//在初始阶段申请一次空间,防止在递归阶段反复申请空间
Msort(A, tempA, 0, A.size()-1);
}