Mushahid Hussain
Mushahid Hussain

Reputation: 4055

Implement Quick sort algorithm with partition of 3 elements,

How to convert this Quick sort algorithm into partition of 3 ,5,7,9 and 11 elements?

#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");
}

Upvotes: 3

Views: 1703

Answers (2)

Howard Hinnant
Howard Hinnant

Reputation: 218980

I think your C++ teacher simply has a poor choice of wording. "partition of 3 elements" almost certainly means: choose the pivot element by picking the median of the first, middle and last elements -- this is the most common coding technique and has good properties when the array is already sorted.

Extrapolate that definition for 5, 7, 9, 11.

Upvotes: 5

gregg
gregg

Reputation: 1027

Partitioning is an essential part of the quicksort algorithm. Review the algorithm to understand what partitioning is. Good luck.

Upvotes: 0

Related Questions