Skip to content

Instantly share code, notes, and snippets.

@gdiggs
Created March 19, 2011 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gdiggs/877794 to your computer and use it in GitHub Desktop.
Save gdiggs/877794 to your computer and use it in GitHub Desktop.
Find top 10 numbers in an array
#include <stdio.h>
#define TOP_NUM 10
// return whether or not an item is in an array
int inArray(int num, int nums[], int nums_size){
int i;
for(i=0; i<nums_size; i++)
if(num == nums[i])
return 1;
return 0;
}
int main(){
int num_nums = 20;
int nums[] = {2, 23, 48, 56, 44, 4, 8, 15, 16, 23, 42, 18, 26, 99, 103, 500, 1, 0, 6, 17};
int i, j;
int top_indices[TOP_NUM];
int curr_max = 0;
for(i=0; i<TOP_NUM; i++){
for(j=0; j<num_nums; j++){
if(inArray(j, top_indices, TOP_NUM)){
continue;
}
if(nums[j] > curr_max){
curr_max = nums[j];
top_indices[i] = j;
printf("new max is %d at index %d\n", curr_max, j);
}
}
curr_max = 0;
}
printf("Indices of top %d values are [ ", TOP_NUM);
for(i=0; i<TOP_NUM; i++){
printf("%d ", top_indices[i]);
}
printf("]\n");
return 1;
}
@mrb
Copy link

mrb commented Mar 19, 2011

I love C

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment