【问题标题】:Implement Quick sort algorithm with partition of 3 elements,实现快速排序算法,划分为 3 个元素,
【发布时间】:2011-04-08 14:15:32
【问题描述】:

如何将这种快速排序算法转换为 3 ,5,7,9 和 11 个元素的分区?

#include"stdafx.h"
#include<iostream>
using namespace std;
#include <stdio.h>
#include <stdlib.h>
#define size 50
void swap(int *x,int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}

int partition(int i,int j )
{
return((i+j) /2);
}

void quicksort(int list[],int m,int n)
{
int key,i,j,k;
if( m < n)
{
k = partition(m,n);
swap(&list[m],&list[k]);
key = list[m];
i = m+1;
j = n;
while(i <= j)
{
while((i <= n) && (list[i] <= key))
i++;
while((j >= m) && (list[j] > key))
j--;
if( i < j)
swap(&list[i],&list[j]);
}

swap(&list[m],&list[j]);
quicksort(list,m,j-1);
quicksort(list,j+1,n);
}
}
void printlist(int list[],int n)
{
int i;
for(i=0;i<n;i++)
printf("%d\t",list[i]);
}

void main()
{
int n,i;
int list[size];


printf("How many numbers do you want to enter");
scanf("%d",&n);
printf("Enter the numbers you want to sort");
for(i=0;i<n;i++)
{
scanf("%d",&list[i]);
}


printf("The list before sorting is:\n");
printlist(list,n);
quicksort(list,0,n-1);
printf("The list after sorting using quicksort algorithm:\n");
printlist(list,n);
system("pause");
}

【问题讨论】:

  • 快速排序中的分区阶段包括将要排序的序列元素重新排列到所选枢轴的左侧或右侧,具体取决于它们分别小于或大于枢轴。不过,不确定“x 的分区”是什么意思。
  • 如果您在 gregg 的回答(和阅读)之后仍有问题,请将它们添加到问题中(如果它们相关),或者创建一个新问题。

标签: java c++ algorithm sorting quicksort


【解决方案1】:

我认为你的 C++ 老师只是在措辞上的选择很差。 “3 个元素的分区”几乎可以肯定的意思是:通过选择第一个、中间和最后一个元素的中位数来选择枢轴元素——这是最常见的编码技术,并且在数组已经排序时具有很好的属性。

将该定义外推为 5、7、9、11。

【讨论】:

  • 我认为这不是糟糕的措辞选择,而是非常棘手的事情。
  • 或者是马而不是斑马:google.com/…
  • 啊,我以为我的想法是分成 4/6/8 个部分,而不是只有两个。
【解决方案2】:

分区是快速排序算法的重要组成部分。查看the algorithm 以了解什么是分区。祝你好运。

【讨论】:

  • 对,但您能否详细说明一下“x 元素的分区”是什么?
  • 是的,我知道枢轴何时出现正确的位置分区。但我还是不知道 x 元素分区的含义。
猜你喜欢
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2020-09-04
  • 2023-01-31
  • 2021-06-12
  • 2018-03-17
  • 2017-05-09
  • 2018-09-20
相关资源
最近更新 更多