c - Accessing and storing elements in an array -


i have modified version of quicksort in program instructed sort pairs of numbers sum of squares ( example: -4,1 > 2,2). program works fine positive integers, when use many negative integers program crashes (any more 1 or 2 negative numbers cause crash). think i'm trying access or sort undefined parts of array storing integers. array storage forgetting? or problem elsewhere?

void swap(int *a,int *b); int square(int num); int abs_value(int num); void quicksort(int arr[],int first,int last);  int main() {    int num_of_pts;    int num1;    int num2;    printf("enter number of points: ");//points coordinates on xy axis    scanf("%d", &num_of_pts);          //that's why there double    int unsorted_pts_arr[2*num_of_pts];//the amount of storage in array    for(int i=0; i<num_of_pts; i++){       printf("enter point: ");       scanf(" %d",&num1);       scanf(" %d",&num2);       unsorted_pts_arr[2*i]=num1;       unsorted_pts_arr[2*i+1]=num2;    }    quicksort(unsorted_pts_arr,0,num_of_pts);    printf("sorted points:");    for(int j=0; j<num_of_pts; j++)       printf(" (%d,%d)",unsorted_pts_arr[2*j],unsorted_pts_arr[2*j+1]);    return 0; }  void swap(int *a,int *b) {    int temp;    temp = *b;    *b = *a;    *a = temp; }  int square(int num) {    num=abs_value(num);    num*=num;    return num; }  int abs_value(int num) {    if(num<0) return -num;    else return num; }  void quicksort(int arr[],int first,int last) {    int pivot,j,i;     if(first<last){       pivot=first;       i=first;       j=last;        while(i<j){          while((square(arr[2*i])+square(arr[2*i+1]))<=                (square(arr[pivot])+square(arr[pivot+1]))                &&i<last)             i++;          while((square(arr[2*j])+square(arr[2*j+1]))>                (square(arr[pivot])+square(arr[pivot+1])))             j--;          if(i<j){             swap(&arr[2*i],&arr[2*j]);             swap(&arr[2*i+1],&arr[2*j+1]);          }       }       swap(&arr[pivot],&arr[2*j]);       swap(&arr[pivot+1],&arr[2*j+1]);       quicksort(arr,first,2*j-1);       quicksort(arr,2*j+1,last);    } } 

main problem

you accessing array out of bounds using 2*j-1 , 2*j+1 array indices in recursive calls.

  quicksort(arr,first,2*j-1);   quicksort(arr,2*j+1,last); 

when call quicksort main, last equal num_of_pts. makes sense in recursive calls, should use j , j+1.

  quicksort(arr,first,j);   quicksort(arr,j+1,last); 

suggestion minor improvement

implementation of square can simpler.

int square(int num) {    return num*num; } 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -