forked from TheAlgorithms/C
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path977.c
33 lines (31 loc) · 823 Bytes
/
977.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/* 1st way: Using 2 pointers */
int *sortedSquares(int *A, int ASize, int *returnSize)
{
int i, start = 0, end = ASize - 1;
int *res = malloc(ASize * sizeof(int));
*returnSize = ASize;
for (i = ASize - 1; i >= 0; i--)
{
if (abs(A[start]) > A[end])
{
res[i] = A[start] * A[start];
start++;
}
else
{
res[i] = A[end] * A[end];
end--;
}
}
return res;
}
/* 2nd way: Using qsort */
int cmpval(const void *a, const void *b) { return *(int *)a - *(int *)b; }
int *sortedSquares(int *A, int ASize, int *returnSize)
{
int *res = malloc(ASize * sizeof(int));
for (int i = 0; i < ASize; i++) res[i] = A[i] * A[i];
*returnSize = ASize;
qsort(res, ASize, sizeof(int), cmpval);
return res;
}