Breaking News

QuickSort in C\C++ (Algorithm, Pseudocode and output)

QuickSort







Hy guys welcome to Another tutorial of Sorting AlgorithmsIn this tutorial, you will learn about QuickSort and it's programming both in C and c++

QuickSort is a popular sorting algorithm that is often faster in practice compared to other sorting algorithms. It utilizes a divide-and-conquer strategy to quickly sort data items by dividing a large array into two smaller arrays. A large array is partitioned into two arrays one of which holds values smaller than the specified value, say pivot, based on which the partition is made and another array holds values greater than the pivot value.
QuickSort partitions an array and then calls itself recursively twice to sort the two resulting subarrays. This algorithm is quite efficient for large-sized data sets as its average and worst-case complexity are of Ο(n2), where n is the number of items.





Partition in QuickSort

Following animated representation explains how to find the pivot value in an array.
Quick Sort Partition Animation
The pivot value divides the list into two parts. And recursively, we find the pivot for each sub-lists until all lists contain only one element.

QuickSort Pivot Algorithm

Based on our understanding of partitioning in Quicksort, we will now try to write an algorithm for it, which is as follows.
Step 1 − Choose the highest index value as pivot
Step 2 − Take two variables to point left and right of the list excluding pivot
Step 3 − left points to the low index
Step 4 − right points to the high
Step 5 − while value at left is less than pivot move right
Step 6 − while value at right is greater than pivot move left
Step 7 − if both step 5 and step 6 does not match swap left and right
Step 8 − if left ≥ right, the point where they met is new pivot

QuickSort Pivot Pseudocode

The pseudocode for the above algorithm can be derived as −
function partitionFunc(left, right, pivot)
   leftPointer = left
   rightPointer = right - 1

   while True do
      while A[++leftPointer] < pivot do
         //do-nothing            
      end while
  
      while rightPointer > 0 && A[--rightPointer] > pivot do
         //do-nothing         
      end while
  
      if leftPointer >= rightPointer
         break
      else                
         swap leftPointer,rightPointer
      end if
  
   end while 
 
   swap leftPointer,right
   return leftPointer
 
end function

Quicksort Algorithm

Using pivot algorithm recursively, we end up with smaller possible partitions. Each partition is then processed for quicksort. We define a recursive algorithm for quicksort as follows −
Step 1 − Make the right-most index value pivot
Step 2 − partition the array using pivot value
Step 3 − quicksort left partition recursively
Step 4 − quicksort right partition recursively

Quicksort Pseudocode

To get more into it, let see the pseudocode for quicksort algorithm −
procedure quickSort(left, right)

   if right-left <= 0
      return
   else     
      pivot = A[right]
      partition = partitionFunc(left, right, pivot)
      quickSort(left,partition-1)
      quickSort(partition+1,right)    
   end if  
   
end procedure


QuickSort Implementation in C



#include<stdio.h>
  
// A utility function to swap two elements

void swap(int* a, int* b)
{
    int t = *a;
    *a = *b;
    *b = t;
}
  

/* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */

int partition (int arr[], int low, int high)
{ int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element for (int j = low; j <= high- 1; j++)
{ // If current element is smaller than the pivot
if (arr[j] < pivot) { i++;
// increment index of smaller element
swap(&arr[i], &arr[j]); } }
swap(&arr[i + 1], &arr[high]); return (i + 1); }

/* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */
void quickSort(int arr[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */
int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition
quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } }


/* Function to print an array */
void printArray(int arr[], int size)
{
    int i;
    for (i=0; i < size; i++)
        printf("%d ", arr[i]);
    printf("\n");
}
  
// Driver program to test above functions
int main()
{
    int arr[] = {10, 7, 8, 9, 1, 5};
    int n = sizeof(arr)/sizeof(arr[0]);
    quickSort(arr, 0, n-1);
    printf("Sorted array: \n");
    printArray(arr, n);
    return 0;
}

Output :


Sorted array: 
1 5 7 8 9 10 


QuickSort Implementation in C++



/* C++ Program - QuickSort */
#include <bits/stdc++.h>
using namespace std; 
  
// A utility function to swap two elements 

void swap(int* a, int* b) 
    int t = *a; 
    *a = *b; 
    *b = t; 
  
/* This function takes last element as pivot, places 
the pivot element at its correct position in sorted 
array, and places all smaller (smaller than pivot) 
to left of pivot and all greater elements to right 
of pivot */

int partition (int arr[], int low, int high) 
    int pivot = arr[high]; // pivot 
    int i = (low - 1); // Index of smaller element 
  
    for (int j = low; j <= high - 1; j++) 
    
        // If current element is smaller than the pivot 
        if (arr[j] < pivot) 
        
            i++; // increment index of smaller element 
            swap(&arr[i], &arr[j]); 
        
    
    swap(&arr[i + 1], &arr[high]); 
    return (i + 1); 
  
/* The main function that implements QuickSort 
arr[] --> Array to be sorted, 
low --> Starting index, 
high --> Ending index */

void quickSort(int arr[], int low, int high) 
    if (low < high) 
    
        /* pi is partitioning index, arr[p] is now 

        at right place */
        int pi = partition(arr, low, high); 
  
        // Separately sort elements before 
        // partition and after partition 

        quickSort(arr, low, pi - 1); 
        quickSort(arr, pi + 1, high); 
    
  
/* Function to print an array */

void printArray(int arr[], int size) 
    int i; 
    for (i = 0; i < size; i++) 
        cout << arr[i] << " "
    cout << endl; 
  
// Driver Code

int main() 
    int arr[] = {10, 7, 8, 9, 1, 5}; 
    int n = sizeof(arr) / sizeof(arr[0]); 
    quickSort(arr, 0, n - 1); 
    cout << "Sorted array: \n"
    printArray(arr, n); 
    return 0; 


Output :


$g++ -o main *.cpp
$main
Sorted array: 
1 5 7 8 9 10 



So this is it guys if you want us to write more on this topic or have any particular query regarding this post you can always comment or feel free to mail us at our official mail also follow us on Instagram and Facebook to receive Latest Updates first.

PEACE!!!


1 comment:

  1. Online marketing is the method of receiving greater
    positioning in the organic search results of Google.com, Yahoo and also MSN.
    The search engines that matter one of the most are actually Google.com along
    with a 62% advertising and marketing allotment Yahoo along with twenty% and MSN
    drifting about along with approximately 10% in market reveal 'that suggests the internet search engine you need to pick
    is actually Google.com cause Google clearly has
    the highest possible percent of folks are actually
    exploring on the net.

    ReplyDelete

If you have any doubts, please let us Know.