Monday, November 14, 2011

Order a vector in C

This tutorial presents two ways of order a vector using the programming language C.
We can use the typical way with two for cicles that can become really slow when the vector length is big (like 3555555) or a less commun way but a faster and smaller (in lines of code).

Typical way:

#include <stdio.h>


int main()
{
int v[5] ={2,5,3,2,4};
int v_temp;
int i,j;
for (i=0; i<5; i++)
{
for (j=0; j<5; j++)
{
if(v[i] <= v[j] && i!=j)
{
v_temp=v[j];
v[j]=v[i];
v[i]=v_temp;
}
}
}
for (i=0; i<5; i++)
{
printf("%d -> %d\n",i,v[i]);
}
return 0;
}


Other way:


#include <stdio.h>


int sort(const void *x, const void *y) {
  return (*(int*)x - *(int*)y);
}


int main()
{
int v[5] ={2,5,3,2,4};
int i;
qsort(v, 5, sizeof(int), sort); /*less lines of code and way faster ordering the vector qsort(name_of_vector,length_of_vector,sizeof(type_of_variable),name_of_function) in this case name_of_function is "sort"*/
for (i=0; i<5; i++)
{
printf("%d -> %d\n",i,v[i]);
}
return 0;
}


The result in both methods it's:

0 -> 2
1 -> 2
2 -> 3
3 -> 4
4 -> 5

1 comment: