quicksort - C Code of hell : quick sort program running to infinite loop : weird situation -


i have written c code quicksort seems ok. code doesn't works , gets weirdly infinte loop or else(which don't know) while taking values array, , nothing after loop takes values.

#include<stdio.h> int flag=0; int partition(int *,int,int); void quicksort(int *a,int low, int high)          //code quicksort function {     int pivot;     printf("%d",flag);     flag++;     if(low<high)     {      pivot =partition(a,low,high);        //calls partition function      quicksort(a,low,pivot);      quicksort(a,pivot,high);     } } //code partition function int partition(int *a,int low,int high) {     int pivot,left,right,temp;     pivot=a[low];     left=low;     right=high;     printf("%d",flag);     flag++;     while(left<right)         {          while(a[left]<pivot)             left++;          while(a[right]>pivot)             right++;          if(left<right)             {              temp=a[left];              a[left]=a[right];              a[right]=temp;             }         }     temp=a[right];     a[right]=a[left];     a[left]=temp;     return right; }  int main()     {         int a[10],i,n;         printf("\n***quick sort***");         printf("\nenter numbers of entries:");         scanf("%d",&n);          printf("\nenter entrties in array:");         //problem in loop or else (i dont know problem is)          for(i=0;i<n;i++)         {             printf("i=%d\n",i);             scanf("%d",&a[i]);              }         //if comment below line of function call loop works fine         quicksort(a,0,n-1);    //passes array , first , last element          printf("\nthe sorted array is:\n");         for(i=0;i<n;i++)             printf(" %d \n ",a[i]);         return 0;     } 

as many have indicated in comments code. need rethink partition step quick sort algorithm - reason encountering infinite loops due fact after swap, left , right never updated causing infinite loop.

this not of own helped me when learning complex sorting algorithms:

void quicksort(int arr[], int left, int right) {   int = left, j = right;   int tmp;   int pivot = arr[(left + right) / 2];   /* partition */   while (i <= j) {         while (arr[i] < pivot)               i++;         while (arr[j] > pivot)               j--;         if (i <= j) {               tmp = arr[i];               arr[i] = arr[j];               arr[j] = tmp;               i++;               j--;         }   }; 

you may find helpful , many have stated may need clean code debugging aspects.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -