快速排序

基本思想:第一趟取一个基点,然后把序列分成两部分,小于基点和大于基点,每一部分再递归调用快速排序。不稳定。

//
//  QuickSort.c
//  libin
//
//  Created by 李宾 on 16/5/9.
//  Copyright © 2016年 李宾. All rights reserved.
//

#include <stdio.h>
#define SWAP(a, b) { int temp; temp = a; a = b; b = temp;}
void Quick_Sort(int *p , int left, int right)
{
    int left_index = left;
    int right_index = right;
    int pivot = p[(left_index + right_index)/2];
    while (left_index <= right_index) {
        while (p[left_index] < pivot) {
            left_index ++;
        }
        while (p[right_index] > pivot) {
            right_index --;
        }
        if (left_index <= right_index) {//相等时候也要交换并加加减减,否则一直递归,栈溢出
            SWAP(p[left_index], p[right_index]);
            left_index ++;
            right_index --;
        }
    }
    if(left_index < right )
    {
        Quick_Sort(p, left_index, right);
    }
    if(right_index > left )
    {
       Quick_Sort(p, left, right_index);
    }
    
}

int main()
{
    int a[5] = { 10 , 4, 13, 6, 29 };
    Quick_Sort(a, 0, 4);
    for (int i = 0; i < 5; i ++) {
        printf("%d\t", a[i]);
    }
    printf("\n");
}

 

posted @ 2016-05-09 13:19  32ddd  阅读(190)  评论(0编辑  收藏  举报