【问题标题】:QuickSort with pivot the middle element not always success使用枢轴中间元素进行快速排序并不总是成功
【发布时间】:2015-04-02 23:25:27
【问题描述】:

我尝试在 c 中编写快速排序,并以数组的中间元素为轴。
但我的程序并不总是显示正确的结果。
这是我的代码:

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

#define SIZE 10  /*max size of array*/

void QuickSort(int [], int, int);
int Partition(int [], int, int);    
void Swap(int *,int *);             

int main()
{
    srand(time(NULL));
    clock_t begin,end;
    double time_spend;
    begin = clock();
    int A[SIZE];
    int i;

    for(i = 0; i < SIZE; i++)  /*full array with numbers 1...100*/
    A[i] = rand() % (100 - 1 + 1) + 1;  

    printf("[");
    for(i = 0; i < SIZE; i++) /*print original array*/
        printf("%d,",A[i]);
    printf("\b]\n");

    QuickSort(A,0,SIZE - 1);  /*start sorting array*/
    printf("\n------After Quick Sorting-----\n");
    printf("\n[");
    for(i = 0; i < SIZE; i++)  /*print sorted array*/
        printf("%d,",A[i]);
    printf("\b]\n");
    end = clock();
    time_spend = (double)(end - begin) / CLOCKS_PER_SEC;
    printf("Elapsed: %f second\n",time_spend);
    return 0;
}
/*recursive function sorting array*/
void QuickSort(int A[], int start, int end)
{
   int i,q;
   if(start < end)
   {
      q = Partition(A,start,end); /*partition array*/
      QuickSort(A,start,q - 1);   /*recursive first half of array*/
      QuickSort(A,q + 1,end);     /*recursive second half of array*/
   }

}
/*function partition with pivot the middle element*/
int Partition(int A[],int start,int end)
{
   int x,i,j;
   x = A[(end + start) / 2];     
   j = start;
   i = end;

   while(j < i)
   {
      while(A[j] < x)
         j++;
      while(A[i] > x)
         i--;
      if(j < i)
      {
          Swap(&A[j],&A[i]);
          j++;
          i--;
      }
  }
  return i;

}
/*function exchange elements*/
void Swap(int* a,int* b)
{
   int temp;
   temp = *a;
   *a = *b;
   *b = temp;
}

我已经尝试更改 epuals 的功能分区,但我无法解决问题。

【问题讨论】:

    标签: c quicksort


    【解决方案1】:

    在你的分区函数中,你需要考虑a[j]==x的情况和a[i]==x的情况。在这种情况下,您不能只是交换它们并照常进行。在纸上检查它,你会看到错误。发生这种情况的示例 - 考虑数组:1 3 4 5 2

    【讨论】:

      猜你喜欢
      • 2022-11-15
      • 2019-11-23
      • 2023-03-04
      • 2014-10-25
      • 2011-08-31
      • 2021-04-19
      • 2015-05-04
      • 1970-01-01
      • 2017-07-11
      相关资源
      最近更新 更多