This blog site is dedicated for articles on problem solving using C, C++, data structures, algorithms. Besides this few technical articles are also presented.
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;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment