C:
#include <iostream>
using namespace std;
#define MAXSIZE 9
//#define MAXSIZE 5
typedef struct
{
int r[MAXSIZE+1];
int length;
}SqList;
void swap(SqList *L, int i ,int j)
{
int temp =L-> r[i];
L-> r[i]=L-> r[j];
L-> r[j]=temp;
}
//快速排序
int Partiton(SqList *L, int low,int high)
{
int pivotkey;
pivotkey=L->r[low];
while (low<high) //1.防止越界 2.防止high比low小 3.循环停止的标志
{
while(low<high && L->r[high]>=pivotkey)
high --;
swap(L,low,high);
while(low <high && L->r[low]<=pivotkey)
low ++;
swap(L,low,high);
}
return low;
}
//快排优化,减少交换次数
int Partiton1(SqList *L, int low,int high)
{
int pivotkey;
pivotkey=L->r[low];
L->r[0]=pivotkey;
while(low<high)
{
while(low<high && L->r[high]>=pivotkey)
high --;
L->r[low]=L->r[high];
while(low <high && L->r[low]<=pivotkey)
low ++;
L->r[high]=L->r[low];
}
L->r[low]=L->r[0];
return low;
}
void QSort(SqList *L,int low,int high)
{
int pivot;
if(low<high)
{
pivot=Partiton(L,low,high);
//pivot=Partiton1(L,low,high);
QSort(L,low,pivot-1);
QSort(L,pivot+1,high);
}
}
void QuickSort(SqList *L)
{
QSort(L,1,L->length);
}
int main()
{
SqList* L = ( SqList* ) malloc( sizeof( SqList ) );//分配内存,初始化
L ->length=9;
for(int i=1;i<=L->length;i++)
{
cin>>L ->r[i];
}
for(int i=1;i<=L->length;i++)
{
cout<<L ->r[i];
}
QuickSort(L);
for(int i=1;i<=L->length;i++)
{
cout<<L ->r[i];
}
}
Python:
L3=[0,50,10,90,30,70,40,80,60,20]
def swap(L,i,j):
temp=L[i]
L[i]=L[j]
L[j]=temp
def Partiton(L,low,high):
pivotkey=L[low]
while (low<high):
while (low < high and L[high] >=pivotkey):
high = high-1
swap(L,low,high)
while (low < high and L[low] <=pivotkey):
low =low + 1
swap(L,low,high)
return low
def QSort(L,low,high):
if(low<high):
pivot=Partiton(L,low,high)
QSort(L,low,pivot-1)
QSort(L,pivot+1,high)
def QuickSort(L):
QSort(L,0,len(L)-1)
if __name__ == "__main__":
QuickSort(L3)
print(L3)