Stanford 算法 part I:第二周编程题

来源:互联网 发布:1100lu.us最新域名是啥 编辑:程序博客网 时间:2024/05/15 11:09

题目如下

这里只列出了核心算法,读入文件的过程省略了,默认读入了array数组
使用语言为C语言

#include<stdio.h>#include<stdlib.h>long merge(long* array,int low,int mid,int high){    long count=0;    int i = low;    int j = mid + 1;    long* temp = array;    for (int k = low; k < high; k++)    {        if (j >= high)            array[k] = temp[i];        else if (i >= mid)            array[k] = temp[j];        else if (temp[i] > temp[j])        {            array[k] = temp[i++];//少写一行i++            count += mid - i + 1;        }        else if (temp[i] < temp[j])        {            array[k] = temp[j++];        }    }    return count;}long count(long* array, int low,int high){    if (high <= low)        return 0;    int mid = low + (high - low) / 2;    long x = count(array, low, mid);    long y = count(array, mid + 1, high);    long z = merge(array, low, mid, high);    return (x + y + z);}
原创粉丝点击