Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

quicksort algorithm

// in c++
#include<iostream>
#include<algorithm>
using namespace std;
int partition(int arr[], int low, int high){
    // i is used for determining the correct position of pivot element
    /*
      We can choose first element of the array as pivot element,
      or we can choose middle element/ last element / any element randomly as pivot element.
       In this program, we are using last element as pivot element.
    */
    int i = low -1;
    int pivot = arr[high];
    for(int j=low; j<= high-1; j++){
        if(arr[j] < pivot){
            i = i+1;
            // to do the swapping directly include "algorithms" library in the header, in c++
            swap(arr[i], arr[j]); 
        }
    }
    // put the pivot elements at its correct position
    swap(arr[i+1], arr[high]);
    return i+1;
}

void quickSort(int arr[], int low, int high){
    if(low < high){
    int pivot = partition(arr, low, high);
    quickSort(arr, low, pivot-1);
    quickSort(arr, pivot+1, high);
    }
}

// for printing the array
void printArray(int arr[], int n){
    for(int i=0; i<n; i++){
        cout<<arr[i]<<" " ;
    }
}
// main function

int main()
{
    int arr[100], pivot, low, high, n;
    cout<<"how many elements you want to put in the array"<<endl;
    cin>>n;
    cout<<endl;
    cout<<"insert elements in the  array"<<endl;
    for(int i =0; i<n; i++){
        cin>>arr[i];
    }
   
    cout<<"Array before Quick Sort"<<endl;
    printArray(arr, n);

     quickSort(arr, 0, n);

    cout<<endl;
    cout<<"Array after quick sort"<<endl;
    printArray(arr, n);

    return 0 ;

    
    
} 
 
PREVIOUS NEXT
Tagged: #quicksort #algorithm
ADD COMMENT
Topic
Name
6+1 =