QuickSort Algorithm Number of Comparisons

淺唱寂寞╮ 提交于 2019-12-11 04:14:26

问题


I have been taking a class at Coursera and we had an assignment which was to count the number of comparisons QuickSort does on a 10,000 size array a numbers.

#include <stdio.h>
#define SIZE 10000

int ComparsionCount = 0;

void swap(int a[], int i, int j) {
        int temp = a[j];
        a[j] = a[i];
        a[i] = temp;
}
int partition(int a[], int l, int r){
        int p = a[l];
        int i = l + 1;
        int j;
        for (j = l + 1; j <= r; j++) {
            if (a[j] < p) {
                swap(a, j, i);
                i++;
            }
        }
        swap(a, l, i - 1);
        return (i - 1);
}
void add(int i) {
    ComparsionCount += i;
}

int QuickSort(int a[], int l, int r){
    int pivot;
    if (r > 1) {
        add(r - 1);
        pivot = partition(a, l, r);
        QuickSort(a, l, pivot - 1);
        QuickSort(a, pivot + 1, r);
    }
    return pivot;
}

int main() {
    FILE *fr;
    int arr[SIZE];
    int i = 0;
    int elapsed_seconds;
    char line[80];

    fr = fopen("QuickSort.txt", "r");
    while (fgets(line, 80, fr) != NULL)
    {
         /* get a line, up to 80 chars from fr.  done if NULL */
         sscanf (line, "%ld", &elapsed_seconds);
         /* convert the string to a int */
         arr[i] = atoi(line);
         i++;
    }
    fclose(fr);  /* close the file prior to exiting the routine */
    printf("%d\n",QuickSort(arr,0,SIZE-1));
}

I am getting an segmentation error. I have identified that the problem lies in two recursive calls of QuickSort.

I have no idea of how to solve this problem,your help would be appreciated a lot Thanks in advance.


回答1:


I think you should add the code in the partition function like this:

for (j = l + 1; j <= r; j++) {
    count++;
    if (a[j] < p) {
    ...
}

Note: count is a global variable initialized to 0.



来源:https://stackoverflow.com/questions/38548503/quicksort-algorithm-number-of-comparisons

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!