动手写快排

自己写了一篇才知道,原来的理解是错误的

并不是high指针和low指针交换,而是直接赋值

一直理解错误,郁闷。


结合http://blog.csdn.net/ppppppppp2009/article/details/9217653 理解


 

#include <stdio.h>

#define SIZE_OF_ARRAY(x) (sizeof(x)/sizeof(x[0]))

void print_array(int array[], int len)
{
        //printf("%d\n", SIZE_OF_ARRAY(array)); 结果为指针大小,数组退化为指针
        int i = 0;
        for(i = 0; i < len; i++)
        {
                printf("%d ", array[i]);
        }
        printf("\n");
        return;
}

int partition(int array[], int low, int high)
{
        printf("low = %d, high = %d\n", low, high);
        print_array(array, 9); 
        int base_num = array[low]; //这里不是array[0], 不能只注意第一次
        while(low < high)    
        {   
                while((low < high) && (array[high] > base_num)) 
                {   
                        high--;
                }   
                array[low] = array[high];
                print_array(array, 9); 

                while((low < high) && (array[low] < base_num))  
                {   
                        low++;
                }   
                array[high] = array[low];
                print_array(array, 9); 
        }   
        array[low] = base_num;
        print_array(array, 9); 
        printf("\n");
        return low;
}
void quick_sort(int array[], int low, int high)
{
        int part_num = 0;
        if(low < high)
        {
                part_num = partition(array, low, high);
                quick_sort(array, low, part_num - 1);
                quick_sort(array, part_num + 1, high);
        }
}

int main()
{
        int array[] = {7, 5, 9, 6, 2, 11, 4, 24, 3};
       // int array[] = {1,2,3,4,5,6,7,8,9};
        int low = 0;
        int high = SIZE_OF_ARRAY(array) - 1;

        quick_sort(array, low, high);
        return 0;
}

 


运行结果



 

posted on 2013-10-08 22:04  you Richer  阅读(166)  评论(0编辑  收藏  举报