Quick Sort Algorithm (C lang) 🎊🎊🌟🌟👍👍

 By: Himanshu Tiwari



QuickSort is a sorting algorithm based on the Divide and Conquer algorithm that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array.

#include<stdio.h>
void printarr(int arr[],int n){
    for(int i=0; i<n; i++){
        printf("%d ",arr[i]);
    }
    printf("\n");
}
int partition(int arr[],int low,int high){
    int pivot=arr[low];//starting point of the array
    int i=low+1;
    int j=high;
    do{
        while (arr[i]<=pivot)
        {
            i++;
        }
        while (arr[j]>pivot)
        {
            j--;
        }
        if(i<j){
            int temp=arr[i];
            arr[i]=arr[j];
            arr[j]=temp;
        }
       
       
    }while(i<j);
    int tempp=arr[low];
    arr[low]=arr[j];
    arr[j]=tempp;

    return j;
}
void quicksort(int arr[],int low,int high){
    int partitionindex;
    if(low<high){
        partitionindex=partition(arr,low,high);
        // printarr(arr,9);
        quicksort(arr,low,partitionindex-1);
        quicksort(arr,partitionindex+1,high);
    }
}
int main(){
int arr[]={2,5,6,8,4,1};
int n=6;
printarr(arr,n);
quicksort(arr,0,n-1);
printarr(arr,n);


    return 0;
}



Comments

Popular Posts