Skip to content

Instantly share code, notes, and snippets.

@gdiggs gdiggs/top10.c
Created Mar 19, 2011

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.