1,插入排序
思想和冒泡排序一样.
从i =1开始遍历,每次把最小值往前放,大的值往后面挤
void InsertSort(int* nums, int numsSize){
for(int i = 1; i<numsSize;i++){
int temp = nums[i];
for(int j = i;j > 0 && nums[j - 1] > temp;j--){
nums[j] = nums[j - 1];
}
nums[j] = temp;
}
}
2,希尔排序
思想:希尔排序本质就是间隔行的排序,比如先排i , i + j , i + 2 * j, i + 3 * j.....然后再排i + 1, i + j + 1,....
话不多说,see see code
void shellsort(int* nums, int numsSize){
int i, j , Incre;
for(Incre = numsSize / 2; Incre > 0; Incre /= 2){
for(int i = Incre;i<N;i++){
int temp = nums[i];
for(j = i; j >= Incre;j -= Incre){
if(temp < nums[j - Incre]){
nums[j] = nums[j - Incre];
}else{
break;
}
}
nums[j] = temp;
}
}
}
3,堆排序
上一讲我们刚聊完堆这个数据结构,想一想这个如何排序呢?
思路很简单:①将数组构建为堆结构
②每次抽走顶层节点,同时下滤一把
void perdown(int* nums, int i, int N){
int child;
int temp;
for(temp = nums[i]; i * 2 <= N;i = child){
child = i * 2 + 1;
if( child != N -1 && nums[child] < nums[child + 1]){
child++;
}
if(temp < nums[child]){
A[i] = A[child];
}else{
break;
}
}
nums[i] = temp;
}
void Heapsort(int* nums, int numsSize){
int i;
//构建一个堆
for(int i = numsSize / 2;i >= 0;i--){
perdown(nums, i , N);
}
for(int i = N-1;i > 0;i--){
Swap(&nums[0], &nums[i]);
perdown(nums, 0, i);
}
}
4, 归并排序
归并排序的思想是经典的分治策略, 将问题分成一些小问题并用递归的方式求解.
最坏复杂度O(nlogn)
①merge 驱动demo
void Merge(int* nums, int* tempnums, int leftpos, int rightpos, int rightend){
int leftend = rightpos - 1;
int temppos = leftpos;
int numsSize = rightpos - leftpos + 1;
while(leftpos <= leftend && rightpos <= rightend){
if(nums[leftpos] > nums[rightpos]){
tempnums[temppos++] = nums[rightpos++];
}else{
tempnums[temppos++] = nums[leftpos++];
}
}
while(leftpos <= leftend){
tempnums[temppos++] = nums[leftpos++];
}
while(right <= rightend){
tempnums[temppos++] = nums[rightpos++];
}
for(int i = 0; i<numsSize ;rightend--){
nums[rightend] = tempnums[rightend];
}
}
②归并排序demo
void Msort(int* nums, int* tempnums, int l, int r){
int mid;
if( l < r){
mid = (l + r)/2;
Msort(nums, tempnums, l, mid);
Msort(nums, tempnums, mid + 1, r);
Merge(nums, tempnums, l, mid + 1, r);
}
}
void Mergesort(int* nums, int numsSize){
int* tempnums = malloc(sizeof(int)*numsSize);
Msort(nums, tempnums, 0, numsSize - 1);
free(tempnums);
}
5,快速排序
平均运行时间N(logN), 最坏情形O(N^2)
快排分四步实现:
①如果S中元素个数是0或1,return
②取S中任意元素称为枢纽元n
③S基于枢纽元分为两个部分 大于n 和 小于 n
④分别进行排序
show code
void quicksort(int* nums, int left, int right){
int key = nums[left];
int i = left;
int j = right;
while(i < j){
while(i < j && nums[j] > key){
j--;
}
nums[i] = nums[j];
while(i < j && nums[i] < key){
i++;
}
nums[j] = nums[i];
}
a[i] = key;
quicksort(nums, left, i - 1);
quicksort(nums, i + 1, right);
}