Showing posts with label quicksort. Show all posts
Showing posts with label quicksort. Show all posts

Mar 7, 2022

sort an array using quicksort

#include #include using namespace std; void printArray(int a[], int len) { for(int i=0;i=r) return; //choose pivot int m = l; //this loop brings all elements < a[l] within m and > a[l] from m+1 to r for(int i=l+1; i<=r; i++) { if(a[i] < a[l]) { m++; int t=a[i]; a[i] = a[m]; a[m] = t; } } //move a[l] to pivot position which will make it rightly positioned in the array int t = a[m]; a[m] = a[l]; a[l] = t; qksort(a, l, m-1); qksort(a, m+1, r); } int main() { // your code goes here int a[] = {8, 12, 16, 4, 0}; cout << "before sorting - "; printArray(a, sizeof(a)/sizeof(a[0])); qksort(a, 0, sizeof(a)/ sizeof(a[0]) - 1); cout << "after sorting - "; printArray(a, sizeof(a)/sizeof(a[0])); return 0; }

Apr 19, 2011

sort an array using quicksort

#include <iostream>
using namespace std;

void mquicksort(int A[], int l, int u)
{
    if(l>=u)
        return;
        
    int m=l;
    
    for(int i=l+1; i<u; i++)
    {
        if(A[i] < A[l])
        {
            int t=A[i];
            A[i] = A[m+1];
            A[m+1]=t;
            m++;
        }
    }

    int t=A[l];
    A[l] = A[m];
    A[m]=t;

    mquicksort(A, l, m-1);
    mquicksort(A, m+1, u);
}

int main() {
    // your code goes here
    int A[20];
    int n;
    cout << "enter number of elements(<=20) to be sorted:";
    cin >> n;
    cout << "\nenter " << n << " elements now\n";
    for(int i=0;i<n;i++)
    {
        cin >> A[i];
    }
    mquicksort(A, 0, n);
    
    cout << "\n\nsorted numbers: ";
    for(int i=0;i<n;i++)
    {
        cout << A[i] << " ";
    }

    return 0;
}