稳定与非稳定的定义可以参照前一博文(稳定排序)
- 插入排序:将已排序区设在数组首部,遍历待交换区找最值,交换到待交换区首/已排序区末。由于是直接交换,是非稳的。
- 快速排序:与归并一样,用的是分治的思想。大致思路是,选数组首元素为基准值,然后使数组首/左指针与尾/右指针相向移动,将比基准值大的元素移到左指针右边,比基准值小的移到右指针左边,可以保证左右指针相交处,右边都比基准值大,左边都比基准值小。(先是左指针左边一定小,右指针右边一定大,逐步逼近相交情况,这样能进行最少次数交换,找到 小-基准值-大 情况)。然后对两边递归快排。
快排 O(nlogn),在数组接近逆序的情况下,退化为 O(n^2),退化为选择排序。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define swap(a, b) __typeof(a) t = a; a = b; b = t
//选择排序,选择最小值,待排序区在最前面
void select_sort(int *num, int n){
int min;
for (int i = 0; i < n - 1; i++){//目标将每个num[i]换为待排序区最小值
min = i;//选一个基准值
for (int j = i + 1; j < n; j++){
if (num[min] > num[j]) min = j;
}
swap(num[i], num[min]);
}
return ;
}
//快排
void quick_sort(int *num, int l, int r){
if (l > r) return;
int x = l, y = r, z = num[x];//基准值为数组第一个元素
while(x < y){//两指针没有相遇
//移动后一个指针使其小于基准值
while(x < y && z < num[y]) y--;
if (x < y) num[x++] = num[y];
while(x < y && num[x] < z) x++;
if (x < y) num[y--] = num[x];
}
//x = y
num[x] = z;
quick_sort(num, l, x - 1);
quick_sort(num, x + 1, r);
return;
}
void out(int *arr, int n){
for(int i = 0; i < n; i++){
printf("%d ", arr[i]);
}
printf("\n");
}
int main(){
srand(time(0));
#define maxop 20
int arr[maxop];
int n = maxop;
while(n--){
arr[n] = rand() % 100;
}
out(arr, maxop);
int test[maxop];
memcpy(test, arr, sizeof(int)*maxop);
//printf("select:");
//select_sort(test, maxop);
printf("quick:");
quick_sort(test, 0, maxop-1);
out(test, maxop);
#undef maxop
return 0;
}