快速排序
快速排序也是典型的分治策略实现,与归并排序不同,快排的关键部分在于
分也就是partition部分,快排平均时间复杂度是O(nlgn),最差时间是O(n^2),属于不稳定排序
实现方法:
#include <stdio.h>
#include <string.h>
//递归快排
int Partition(int *ar,int low,int high) //快速排序的一次划分
{
int tmp=ar[low];
while(low < high)
{
while(low < high && ar[high] >= tmp)
{
high–;
}
ar[low]=ar[high];
while(low < high && ar[low] <= tmp)
{
low++;
}
ar[high]=ar[low];
}
ar[low]=tmp;
return low;
}
static void Quick(int *ar,int low,int high)
{
int par=Partition(ar,low,high);
if(low+1 < par) //左边至少两个数据
{
Quick(ar,low,par-1);
}
if(par+1 < high) //右边至少两个数据
{
Quick(ar,par+1,high);
}
}
void QuickSort(int *arr,int len)
{
Quick(arr,0,len-1);
}
int main()
{
int arr[]={1,2,3,54,6,87,9,8,56,54,3,4,22};
int len=sizeof(arr)/sizeof(arr[0]);
QuickSort(arr,len-1);
for(int i=0;i<len;i++)
{
printf("%d ",arr[i]);
}
return 0;
}
//非递归快排
.h头文件中
#pragma once
#define INITSIZE 10
typedef struct SeqStack
{
int *elem;
int top;数据有效个数
int stacksize;栈大小
}SeqStack,*PSeqStack;
void InitStack(PSeqStack ps); //初始化
bool Push(PSeqStack ps,int val); //入栈
bool GetTop(PSeqStack ps,int *rtval); //获取栈针所指栈内元素
bool Pop(PSeqStack ps,int *rtval); //出栈
bool IsEmpty(PSeqStack ps); //判空
void Destroy(PSeqStack ps); //销毁
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include “0721.h”
void InitStack(PSeqStack ps)
{
assert(ps != NULL);
ps->elem = (int *)malloc(sizeof(int)*INITSIZE);
ps->top = 0;
ps->stacksize = INITSIZE;
}
static bool IsFull(PSeqStack ps) //扩容
{
return ps->top == ps->stacksize;
}
bool Push(PSeqStack ps,int val)//O(1)
{
if(IsFull(ps))
{
ps->elem = (int )realloc(ps->elem,ps->stacksize2*sizeof(int));
ps->stacksize *= 2;
}
ps->elem[ps->top++] = val;
//ps->top++;
return true;
}
bool GetTop(PSeqStack ps,int *rtval)
{
if(IsEmpty(ps))
{
return false;
}
*rtval = ps->elem[ps->top-1];
return true;
}
bool Pop(PSeqStack ps,int *rtval)//O(1)
{
if(IsEmpty(ps))
{
return false;
}
*rtval = ps->elem[--ps->top];
//ps->top--;
return true;
}
bool IsEmpty(PSeqStack ps)
{
return ps->top == 0;
}
void Destroy(PSeqStack ps)
{
free(ps->elem);
ps->elem = NULL;
ps->top = 0;
ps->stacksize = 0;
}
void QuickSort2(int *arr,int len)//O(n),O(logn),不稳定
{
SeqStack s;
InitStack(&s);
int low = 0;
int high = len-1;
int par = Partition(arr,low,high);
if(low+1 < par)
{
Push(&s,low);
Push(&s,par-1);
}
if(par+1 < high)
{
Push(&s,par+1);
Push(&s,high);
}
while(!IsEmpty(&s))
{
Pop(&s,&high);
Pop(&s,&low);
par = Partition(arr,low,high);
if(low+1 < par)
{
Push(&s,low);
Push(&s,par-1);
}
if(par+1 < high)
{
Push(&s,par+1);
Push(&s,high);
}
}
Destroy(&s);
}
int main()
{
int arr[]={3,1,5,6,6,5,7,23,65,47,8,89,100,97,};
int len=sizeof(arr)/sizeof(arr[0]);
QuickSort2(arr,len);
for(int i=0;i<len;i++)
{
printf("%d \n",arr[i]);
}
return 0;
}