Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

quicksort implementation

Tags:

c++

quicksort

Following code for quicksort does not work and I can't understand what is reason.

#include <iostream>
using namespace std;
void exch(int a[],int i,int j){
    int s=a[i];
    a[i]=a[j];
    a[j]=s;

}
int  partition(int a[],int l,int h);
void quick(int a[],int l,int h){
    if (h<=l) return ;
    int j=partition(a,l,h);
    quick(a,l,j-1);
    quick(a,j+1,h);
    }
int partition(int a[],int l,int h){
    int i=l-1;
    int j=h;
    int v=a[l];
    while(true){

        while( a[++i]<v);

        while(a[--j]>v) if (j==i)  break;

            if (i>=j) break;

        exch(a,i,j);

    }

    exch(a,i,h);
    return i;



}
int main(){

    int a[]={12,43,13,5,8,10,11,9,20,17};
    int n=sizeof(a)/sizeof(int);
quick(a,0,n-1);
 for (int  i=0;i<n;i++){
     cout<<a[i]<<"  ";
 }
     return 0;
 }

It outputs

5  8  9  11  10  17  12  20  13  43
like image 765
dato datuashvili Avatar asked Oct 02 '11 05:10

dato datuashvili


People also ask

What is the working principle of quicksort?

Quicksort is a divide-and-conquer algorithm. It works by selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. For this reason, it is sometimes called partition-exchange sort.

What is quick sort explain with example?

Quick Sort is a sorting algorithm, which is commonly used in computer science. Quick Sort is a divide and conquer algorithm. It creates two empty arrays to hold elements less than the pivot value and elements greater than the pivot value, and then recursively sort the sub arrays.

Which technique is used in Quicksort?

Quicksort algorithm uses divide and conquer technique, because it solves the problem by recursively dividing the problem into parts, until problem becomes trivial.


1 Answers

In your partition method, that should be

int v = a[h]; 

and not

int v = a[l];

[Update: I've just tested the code with that change, and it works correctly, outputting:

5  8  9  10  11  12  13  17  20  43 
like image 164
Mitch Wheat Avatar answered Sep 19 '22 10:09

Mitch Wheat