Domanda

I'm having issues with a small portion of my program that makes a list of random numbers and then shell sorts them, right now it will not finish computing, which makes me think that the loop isn't finishing. I WAS getting segmentation fault errors but I managed to fix that by fixing some issues with how I was accessing my Array. Anyways, a fresh set of eyes may be good for me.

THANKS!

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{

    printf("How long would you like to make the list? \n");

    int list_length;
    scanf("%d", &list_length);

    int *number_list[list_length];
    int random_number;
    int i;
    for(i=0; i<list_length; i++){
        srand ( time(NULL) );
        random_number = rand();
        number_list[i] = random_number; 
    }

    printf("Before: ");
    printf("%d", &number_list[0]);
    printf("\n");
    shellSort(*number_list, list_length);

    printf("After: ");
    printf("%d", &number_list[0]);
    printf("\n");

    return 0;
}

void shellSort(int *A, int n){
int gap , i , j , temp; 

for (gap = n/2; gap>0; gap /=2)
    for (i=gap; i<n; i++)
        for(i = i-gap; j>=0 && &A[j] > &A[j+gap]; j-=gap){
            temp = &A[j]; 
            A[j] = &A[j + gap]; 
            A[j + gap] = temp; 
        }
}
È stato utile?

Soluzione

Maybe you should use j instead of i in this line:

 for(j = i-gap; j>=0 && &A[j] > &A[j+gap]; j-=gap) // <- first i is replaced by j
//   ^ 
//   Here

Altri suggerimenti

In this line for(i = i-gap; j>=0 && &A[j] > &A[j+gap]; j-=gap){ you are initializing i, however you decrement and check j. You should change the left side of assignment operator from i to j.

Your code shouldn't even compile. You declare number_list as an array of pointers to int but then assign it an int. You also can't declare arrays of non-constant size in C89.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top