I am working on a code I want to optimize. The code is all about sorting a double array by ascending order of its second .
The first input is an integer N, and the second is a 2D array of size N*2 (call it c), then we sort the array by ascending order of c[.][1], and when there are equal elements, say if c[i][1]==c[j][1], for two integers i and j, we sort those elements by ascending of the elements of the first columns, so c[i][1] is below c[j][1] if c[i][1]<c[j][1]. Let’s take an example :
input
3
2 3
1 3
4 2
output
4 2
1 3
2 3
The fact is that the code needs to run in less than 0.5s and mine is really too slow. Here it is
#include <stdio.h>
#include <stdlib.h>
//determining the index of the max elments in an array
int max(int i, int N, int **c)
{
int j=0;
int M=0;
for(j=0;j<i;j++)
{if(c[j][1]>c[M][1]){M=j;}else{}}
return M;
}
int main ()
{
//integers used for the loops
int i;
int j;
//the size of the 2D array is N*2
int N;
scanf("%d",&N);
int **c;
int mx;
int maxi;
//this array is the output, thath is the 2D array sorted
int e[N][2];
//2D array we want to sort
c = malloc(N*sizeof(int*));
for (i=0;i<N;i++)
{
c[i] = malloc(2*sizeof(int));
for (j=0;j<2;j++)
{
scanf("%d",&c[i][j]);
}
}
//at the first step, we have initialized the value of the max
maxi=max(N,N,c);
for(i=0;i<N;i++)
{
//we sort the c[.][1], and we take the max (called 'mx') of the array. At each step of the loop, we throw away the max from the array c[.][1] (we mean the max found at the precedent step of the loop)
mx=max(N-i,N,c);
//Here, we look at the multiple occurence of the max, if there are, we sort the c[.][0] for which c[.][1]=c[mx][1] by ascending order
if(maxi==mx){int k;
for(k=0;k <N;k++){if(c[k][1]==c[mx][1]){if(c[k][0]>c[mx][0]){mx=k;}}else{}}
}else{}
//we keep the value of the max in order to verify that the same value of the max has another occurence in following steps
maxi=mx;
//e is the double array for the output
e[i][0]=c[mx][0];
e[i][1]=c[mx][1];
int j;
//here we throw away the max from the array
for(j=mx;j< N-i-1;j++){c[j][1]=c[j+1][1];c[j][0]=c[j+1][0];}
}
for(i=0;i<N;i++)
{printf("%d %d",e[N-1-i][0],e[N-1-i][1]);
printf("\n");}
}
Could anyone help ?
Your code has way too high computational complexity. Also,
int e[N][2]only works under GCC extension sinceNis a variable determined at run time instead of compile time.An easy (in terms of coding) way to improve it is utilizing
qsort()in C standard library.Edit: to answer the question in comment “could each element of the N-dynamic allocation points to 1D array of size 2?”