The following code shows a C Program for Implementing Quick Sort. Also, the pivot element has been taken as the last element in the array.
// Implementation of Quick Sort in C
#include <stdio.h>
#include <stdlib.h>
int Partition(int myarray[], int first, int last);
void Swap(int myarray[], int i, int j);
void QuickSort(int myarray[], int first, int last)
{
if(first<last)
{
int mypivot=Partition(myarray, first, last);
QuickSort(myarray, first, mypivot-1);
QuickSort(myarray, mypivot+1, last);
}
else
{
return;
}
}
int Partition(int myarray[], int first, int last)
{
int i, j, x, mypivot;
//Taking a last element as pivot element
mypivot=myarray[last];
i=first-1;
for(j=first;j<last;j++)
{
if(myarray[j]<mypivot)
{
i++;
Swap(myarray, i, j);
}
}
Swap(myarray, i+1, last);
return i+1;
// return 1;
}
void Swap(int myarray[], int i, int j)
{
int t=myarray[i];
myarray[i]=myarray[j];
myarray[j]=t;
}
int main()
{
int i, j, elements_count;
int myarray[]={12, 3, 9, 56, -78, 34, -2, -9, 10, 88, 7, 16};
elements_count=sizeof(myarray)/sizeof(int);
printf("Original Array....\n");
for(i=0;i<elements_count;i++)
printf("%d ", myarray[i]);
printf("\n\n");
QuickSort(myarray, 0, elements_count-1);
printf("Sorted Array....\n");
for(i=0;i<elements_count;i++)
printf("%d ", myarray[i]);
printf("\n\n");;
return 0;
}
Output
Further Reading
50+ C Programming Interview Questions and Answers
C Program to Find Factorial of a Number
- AI
- Android
- Angular
- ASP.NET
- Augmented Reality
- AWS
- Bioinformatics
- Biometrics
- Blockchain
- Bootstrap
- C
- C#
- C++
- Cloud Computing
- Competitions
- Courses
- CSS
- Cyber Security
- Data Science
- Data Structures and Algorithms
- Data Visualization
- Datafication
- Deep Learning
- DevOps
- Digital Forensic
- Digital Trust
- Digital Twins
- Django
- Docker
- Dot Net Framework
- Drones
- Elasticsearch
- ES6
- Extended Reality
- Flutter and Dart
- Full Stack Development
- Git
- Go
- HTML
- Image Processing
- IoT
- IT
- Java
- JavaScript
- Kotlin
- Latex
- Machine Learning
- MEAN Stack
- MERN Stack
- Microservices
- MongoDB
- NodeJS
- PHP
- Power Bi
- Projects
- Python
- Quantum Computing
- React
- Robotics
- Rust
- Scratch 3.0
- Shell Script
- Smart City
- Software
- Solidity
- SQL
- SQLite
- Tecgnology
- Tkinter
- TypeScript
- VB.NET
- Virtual Reality
- Web Designing
- WebAssembly
- XML