You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
6. 快 速 排 序
6.1 描 述
快 速 排 序 使 用 分 治 法 来 把 一 个 串 ( list ) 分 为 两 个 子 串 ( sub - lists ) 。 具 体 算 法 描 述 如 下 :
( 1 ) 从 数 列 中 挑 出 一 个 元 素 , 称 为 “ 基 准 ” ( pivot ) ;
( 2 ) 重 新 排 序 数 列 , 所 有 元 素 比 基 准 值 小 的 摆 放 在 基 准 前 面 , 所 有 元 素 比 基 准 值 大 的 摆 在 基 准 的 后 面 ( 相 同 的 数 可 以 到 任 一 边 ) 。
在 这 个 分 区 退 出 之 后 , 该 基 准 就 处 于 数 列 的 中 间 位 置 。 这 个 称 为 分 区 ( partition ) 操 作 ;
( 3 ) 递 归 地 ( recursive ) 把 小 于 基 准 值 元 素 的 子 数 列 和 大 于 基 准 值 元 素 的 子 数 列 排 序 。
6.2 复 杂 程 度
时 间 复 杂 度 O ( nlog2n )
空 间 复 杂 度 O ( nlog2n )
6.3 代 码
# include <stdio.h>
void Swap ( int * , int * ) ; //函数声明, 交换两个变量的值
void QuickSort ( int * , int , int ) ; //函数声明, 快速排序
int main ( void )
{
int i ; //循环变量
int a [ ] = { 22 , 34 , 3 , 32 , 82 , 55 , 89 , 50 , 37 , 5 , 64 , 35 , 9 , 70 } ;
QuickSort ( a , 0 , 14 ) ;
printf ( " 最终排序结果为: \n " ) ;
for ( i = 0 ; i < 14 ; + + i )
{
printf ( " %d " , a [ i ] ) ;
}
printf ( " \n " ) ;
return 0 ;
}
void Swap ( int * p , int * q )
{
int buf ;
buf = * p ;
* p = * q ;
* q = buf ;
return ;
}
void QuickSort ( int * a , int low , int high )
{
int i = low ;
int j = high ;
int key = a [ low ] ;
if ( low > = high ) //如果low >= high说明排序结束了
{
return ;
}
while ( low < high )
{
while ( low < high & & key < = a [ high ] )
{
- - high ;
}
if ( key > a [ high ] )
{
Swap ( & a [ low ] , & a [ high ] ) ;
+ + low ;
}
while ( low < high & & key > = a [ low ] )
{
+ + low ;
}
if ( key < a [ low ] )
{
Swap ( & a [ low ] , & a [ high ] ) ;
- - high ;
}
}
QuickSort ( a , i , low - 1 ) ; //用同样的方式对分出来的左边的部分进行同上的做法
QuickSort ( a , low + 1 , j ) ; //用同样的方式对分出来的右边的部分进行同上的做法
}
6.4 运 行 时 间
0.02485 s