快速实施的麻烦

时间:2017-10-03 14:41:06

标签: c debugging out-of-memory quicksort

我遇到了执行快速排序算法的问题。 这是我遇到的错误,但无法找到问题所在。如果有人能指出错误在哪里,我将感激不尽。

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

void main(){
    int arr[] = {10, 7, 8, 9, 1, 5};
    int n = sizeof(arr)/sizeof(arr[0]);
    quickSort(arr,0,n-1);
    printArray(arr,0,n-1);
}

//Quicksort Function
void quickSort(int arr[],int low,int high){
    if (low < high){

        int pi=partition(arr,low,high);
        quickSort(arr,low,pi-1);//takes care of lower set of numbers
        quickSort(arr,pi+1,high);//takes care of higher elements above pivot
    }
}

//Function for partitioing, in my program i am cosidering pivot as the element at high or the last element
int partition(int arr[],int low,int high){
    int i,j;
    i=(low-1);
    int pivot=arr[high];
    for(j=low;j<=high;j++){
        if(arr[j]<=pivot){
            i++;
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i+1], &arr[high]);
    return (i+1);
}

//function to print array
void printArray(int arr[],int low,int high){
    int i;
    for(i=low;i<=high;i++){
        printf("%d ",arr[i]);
    }
}

//function to swap two elements of array
void swap(int* a, int* b)
{
    int t = *a;
    *a = *b;
    *b = t;
}

2 个答案:

答案 0 :(得分:0)

QuickSort算法的简单实现

 void q_sort(int v[],int left,int right)
 {
   int i,last;

   if(left>=right)
   return;

   swap(v,left,(left+right)/2);
   last=left;

   for(i=left+1;i<=right;i++)
      if(v[i]<v[left])
        swap(v,++last,i);

   swap(v,left,last);
   q_sort(v,left,last-1);
   q_sort(v,last+1,right);  
}

void swap(int v[],int i,int j)
{
   int temp;
   if(i!=j){
       temp=v[i];
       v[i]=v[j];
       v[j]=temp;
   }
}

答案 1 :(得分:0)

问题出在你的分区() -

的这个陈述中
        if(arr[j]<=pivot){

将其更改为 -

        if(arr[j]<pivot){