//SwapSort.h
#ifndef _SWAPSORT_H_
#define _SWAPSORT_H_
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define SIZE 15
typedef int Element;
typedef Element ListType[SIZE];
void CreateRandom(ListType List, int n);
void print(ListType List, int n);
//冒泡排序
void BubbleSort(ListType List, int n);
//快速排序
void QuickSort(ListType List, int n );
#endif //_SWAPSORT_H_
//SwapSort.c
#include "SwapSort.h"
void CreateRandom(ListType List, int n)
{
int i = 0;
srand((unsigned)time(NULL));
for (i = 0; i < n; ++i)
{
List[i] = rand() % 0x7F;
}
}
void print(ListType List, int n)
{
int i = 0;
for (i = 0; i < n; ++i)
{
printf("%d\t", List[i]);
}
printf("\n");
}
static void Swap(Element *a, Element *b)
{
Element Temp = *b;
*b = *a;
*a = Temp;
}
void BubbleSort(ListType List, int n)
{
int i = 0, j = 0;
for (i = 0; i < n-1; i++) //n个元素需要n-1趟排序
{
for (j = 0; j < n-i-1; j++) //每趟 n - i - 1个元素参与交换,因为每趟都会有一个最大的元素到达顶端,不用管已经达到顶端的元素
{
if( List[j] >List[j + 1] )
Swap(&List[j], &List[j + 1]);
}
}
}
/**************************************************
采用分治思想将原来的以一个标志位数组分割成两个部分,再
在已分割的部分再进行分割
**************************************************/
void QuickSort(ListType List, int n)
{
if( n <= 0 )
return ;
int i = 0, j = 0, high = 0, low = 0;
Element pivot = List[0]; //取首元素作为轴值,同时作为辅助空间保存轴元素值
low = 0;
high = n - 1;
while (low < high) //将low到high范围的所有数据分割成两部分,右部分全部大于(或等于)轴值,左部分全部小于(或等于)轴值
{
while (low < high && List[high] >= pivot) //大于或等于轴值的元素无需进行交换操作,移动指针,等于时移动指针是为了稳定性
high--;
if( low < high ) //必须判断是否是因为不满足low < high而停止遍历,如果元素成分复杂,赋值就是个耗时操作,避免无意义的自赋值带来性能上的损耗
List[low] = List[high]; //将大于轴值的元素[high]拿过来覆盖[low], 由于轴值为[low],因此两个改变指针的循环的位置不能对换,否则将会丢失元素)
while (low < high && List[low] <= pivot) //赋值完成后改变遍历的指针继续遍历
low++;
if (low < high)
List[high] = List[low]; //将大于的元素赋值到轴的右边
}
List[low] = pivot; //在分割点插入轴值
QuickSort(List, low ); //对左部分排序
QuickSort(&List[low + 1], n - low - 1); //对右部分排序
}
//main.c
#include "SwapSort.h"
int main(int argc, char **argv)
{
ListType List ={ 0 };
int n = sizeof(List) / sizeof(Element);
CreateRandom(List, n);
printf("排序前\n");
print(List, n);
//BubbleSort(List, n);
QuickSort(List, n);
printf("排序后\n");
print(List, n);
system("pause");
return 0;
}
快速排序的分割过程是这样的