Skip to content

Commit eb5a450

Browse files
Add c smaller numbers algorithm
1 parent 1989d2a commit eb5a450

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
int cmpfunc(const void * a, const void * b) {
2+
return ( *(int*)a - *(int*)b );
3+
}
4+
5+
6+
/**
7+
* Note: The returned array must be malloced, assume caller calls free().
8+
*/
9+
int* smallerNumbersThanCurrent(int* nums, int numsSize, int* returnSize) {
10+
int *res = malloc(sizeof(int) * numsSize);
11+
*returnSize = numsSize;
12+
13+
int * numsCpy = malloc(sizeof(int) * numsSize);
14+
for(int i = 0; i < numsSize; ++i)
15+
numsCpy[i] = nums[i];
16+
17+
qsort(numsCpy, numsSize, sizeof(int), cmpfunc);
18+
19+
for(int i = 0; i < numsSize; ++i) {
20+
int ii = 0;
21+
while(numsCpy[ii++] != nums[i]);
22+
23+
res[i] = ii-1;
24+
}
25+
26+
free(numsCpy);
27+
28+
return res;
29+
}

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ Click to expand the 9 *C programs*!
3232
- reverse an array in place
3333
- reverseStr.c
3434
- reverse string
35+
- smallerNumbersThanCurrent
36+
- Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it.
3537
- squareCalc.c
3638
- return the square of a number with just addition
3739
- inductive assert

0 commit comments

Comments
 (0)