排序算法-快速排序算法
快速排序采用的思想是分治思想,是对要进行排序的数据分割成独立的两部分,其中一部分的数据要比另一部分的数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
代码如下:
///所有排序算法的基本结构体
typedef struct
{
int data[MAX_SIZE + 1];//数据
int length;//长度
}SqList;
//交换两个数据
void Swap(SqList *list ,int i,int j)
{
if(!list) return;
int temp = list->data[i];;
list->data[i] = list->data[j];
list->data[j] = temp;
}
void printfSqList(SqList *list)
{
if (list) {
for (int i =0; i< list->length; i++) {
printf("%d ",list->data[i]);
}
}
}
//交换list中子表的记录,确定枢轴,返回其位置
int Partition(SqList *list,int low,int high)
{
int pivotKey;
int m = low + (high - low)/2;
if (list->data[low]>list->data[high]) {
Swap(list, low, high);//交换左端与右端,始左端较小
}
if (list->data[m]>list->data[high]) {
Swap(list, high, m);//交换中间与右端,使中间较小
}
if (list->data[m]>list->data[low]) {
Swap(list, high, m);//交换中间与左端,使左端较小
}
pivotKey = list->data[low];
while (low<high) {
while ( low<high && list->data[high]>=pivotKey) {
high--;
}
Swap(list, low, high);//交换,将比pivot小的值换到low;
while ( low<high && list->data[low]<=pivotKey) {
low++;
}
Swap(list, low, high);
}
return low;
}
//对list->data[low...high]做排序。low:最小下标,high:最大下标
void QuickSort(SqList *list,int low,int high)
{
int pivot;//枢轴
if (low<high) {
pivot = Partition(list,low,high);
QuickSort(list, low, pivot-1);
QuickSort(list, pivot+1, high);
}
}
main方法中加入
{
int array[] = {7,6,9,10,5,1,8};
SqList listStruct;
printf("source data:");
SqList *plist = &listStruct;
for (int i =0 ; i<7; i++) {
plist->data[i] = array[i];
printf("%d ",plist->data[i]);
}
plist->length = 7;
printf("\r\n");
QuickSort(plist, 0, 6);
printf("final data :");
printfSqList(plist);
}
objcetive-c下的实现
- (void)quickSort:(NSMutableArray *)mArray low:(int)low hight :(int)high
{
if (low>=high) {
return;
}
int tempLow = low;
int tempHigth = high;
NSInteger povitPosition = 0;
NSNumber *povitNumber = [mArray objectAtIndex:low];//确定枢轴值,当前设为low的值
//枢轴
while (low<high) {
while ((low<high) && ( [( NSNumber *)[mArray objectAtIndex:high] integerValue] >=povitNumber.integerValue)) {
high--;
}
[mArray exchangeObjectAtIndex:low withObjectAtIndex:high];
while (low<high && [(NSNumber *)[mArray objectAtIndex:low] integerValue] <=povitNumber.integerValue ) {
low++;
}
[mArray exchangeObjectAtIndex:low withObjectAtIndex:high];
}
povitPosition = low;
[self quickSort:mArray low:tempLow hight:povitPosition-1];
[self quickSort:mArray low:povitPosition+1 hight:tempHigth];
}
在此基础上还可以对快速算法进行优化,有时间了在搞。