Algorithm that finds the first 20 closest numbers to 23
I'm trying to figure out how to find the first 20 numbers that are closest to 23 in an int array of 200 between numbers 1 - 100. I tried to break it into steps:
-subtract each number in the array by 23
-get the absolute value of that number
-use selection sort to get the smallest numbers
...and thats where I'm stuck. I can't just add 23 back to those numbers, because some were negative. Right now I'm getting a segmentation fault. Any help?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define ARRAY_SIZE 200
#define NUM_TO_FIND 20
int main(int argc, char *argv[]) {
int numbers[ARRAY_SIZE];
int top[NUM_TO_FIND];
int idx;
int i;
int j;
int k;
int hold;
srand(time(NULL));
memset(&top[0], 0, sizeof(int) * NUM_TO_FIND);
for (idx = 0; idx < ARRAY_SIZE; idx++){
numbers[idx] = rand() % 99 + 1;
}
//here
for (k = 0; k < ARRAY_SIZE; k++){
top[k] = numbers[k] - 23;
top[k] = top[k]<0?0-top[k]:top[k];
}
for(i = 0; i < ARRAY_SIZE; i++){
for(j = 0; j < ARRAY_SIZE; j++){
if(top[i] < top[j]){
hold = top[i];
top[i] = top[j];
top[j] = hold;
}
}
}
//here
puts("Original Array:");
for (idx = 0; idx < ARRAY_SIZE; idx++)
printf("%d ", numbers[idx]);
puts("\nTop 20:");
for (idx = 0; idx < NUM_TO_FIND; idx++)
printf("%d ", top[idx]);
return 0;
}