\$\begingroup\$
\$\endgroup\$
Please look the code below
#include<stdio.h>
void quicksort(int *,int ,int);
int partition1(int *,int ,int);
void swap1(int *,int *);
int main()
{
int low = 0;
int length;
int i;
int a[100];
int high;
printf("Enter the length of array\n");
scanf("%d",&length);
high=length-1;
printf("Enter the array elememts\n");
for(i=0;i<=high;i++)
{
scanf("%d",&a[i]);
}
quicksort(a,low,high);
printf("The sorted array\n");
for(i=low;i<=high;i++)
{
printf("%d--",a[i]);
}
printf("\n");
return 0;
}
void quicksort(int a[],int low,int high)
{
int p;
if(low<high)
{
p=partition1(a,low,high);
quicksort(a,low,p-1);
quicksort(a,p+1,high);
}
}
int partition1(int a[],int low,int high)
{
int pivot=a[high];
int i=low-1;
int j=low;
for(j=low;j<high;j++)
{
if(a[j]<a[high])
{
i++;
swap1(&a[i],&a[j]);
}
}
swap1(&a[i+1],&a[high]);
return i+1;
}
void swap1(int* a,int* b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
This is the working program of quick sort.Can anyone tell me the way to make this program much better?
please do the necessary changes required.
asked Jul 14, 2016 at 7:38
1 Answer 1
\$\begingroup\$
\$\endgroup\$
Coding conventions
- Have at least one empty line after all
#include
s. - Have one space character before and after every binary operator. For example,
a + 1
instead ofa+1
. That makes your code easier to read. - Have one space after each
for
keyword: notfor(i=1;i<10;i++)
, but rather
for (i = 1; i < 10; i++)
. (Same applies toif
.) - Fix your indentation:
for(j=low;j<high;j++) { if(a[j]<a[high]) { i++; swap1(&a[i],&a[j]); } }
to
for(j=low;j<high;j++) { if(a[j]<a[high]) { i++; swap1(&a[i], &a[j]); } }
- Instead of writing
&a[index]
you can write simplya + index
. - Whenever printing a simple (non-formated) standard output, use
puts
instead ofprintf
. (Also, note thatputs
automatically adds the new line character after the argument string.)
All the above points are relevant to readability of your source code.
Summa summarum
All in all, I had this in mind:
#include<stdio.h>
void quicksort(int*, int, int);
int partition(int*, int, int);
void swap(int*, int*);
int main()
{
int low = 0;
int length;
int i;
int a[100];
int high;
puts("Enter the length of array:");
scanf("%d", &length);
high = length - 1;
puts("Enter the array elements:");
for (i = 0; i <= high; i++)
{
scanf("%d", &a[i]);
}
quicksort(a, low, high);
puts("The sorted array:");
for (i = low; i <= high; i++)
{
printf("%d ",a[i]);
}
puts("");
return 0;
}
void quicksort(int a[],int low,int high)
{
int p;
if (low < high)
{
p = partition(a, low, high);
quicksort(a, low, p - 1);
quicksort(a, p + 1, high);
}
}
int partition(int* a, int low, int high)
{
int pivot = a[high];
int i = low;
int j;
for (j = low; j < high; ++j)
{
if (a[j] <= pivot)
{
swap(a + i++, a + j);
}
}
swap(a + i, a + high);
return i;
}
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
Hope that helps.
answered Jul 14, 2016 at 10:40
lang-c