排序相关

合并排序

扩展题目

1.求数组中反序对的个数

解法:

将数组进行合并排序,只要P2指针向后移动,反序个数就sum += mid-p1+1个。如图,将2加入结果,<3,2> <5,2>都是反序的。

 

2.荷兰国旗问题

o(n)时间,o(1)空间,将0,1,2三个数排好序。

解法:

排好序的数组分为三个区,最左边是0,最右边是2,其余的都在中间。

利用这个思想,维护三个变量begin,current,end

其中在begin左边的都是0,在end右边的都是2。current一直遍历到current=end。

具体步骤:

1、current遍历,整个数组序列,current指1不动,
2、current指0,与begin交换,而后current++,begin++,
3、current指2,与end交换,而后,current不动,end--。

int fun(char* str,int len){
    if(str==NULL || len<1){
        return -1;
    }
    int begin = 0;
    int current = 0;
    int end = len-1;
    char c;
    while(current<=end){
        if(*(str+current)>(int)'1'){
            c = *(str+current);
            *(str+current) = *(str+end);
            *(str+end) = c;
            end--;
        }
        if(*(str+current)<(int)'1'){
            c = *(str+current);
            *(str+current) = *(str+begin);
            *(str+begin) = c;
            begin++;
        }
        current++;
    }
    return 0;
}

int main(){
    char* str = malloc(sizeof(char)*100);
    strcpy(str,"012210"); 
    printf("整理前:%s\r\n",str);
    fun(str,strlen(str));
    printf("整理后:%s\r\n",str);
    return 0;
}
posted @ 2012-10-01 10:25  23lalala  阅读(141)  评论(0编辑  收藏  举报