Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
}
like image 959
james Avatar asked May 30 '26 22:05

james


1 Answers

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.

like image 187
Howard Hinnant Avatar answered Jun 01 '26 11:06

Howard Hinnant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!