-
Sorting Arrays???
I've just started c and java this semester and and I'm writting a small program that calculates your handicap. :D
Basically all my calculation gets put into an array. But I have no idea how to get the information from that array.
The array holds 20 integers. I need to find the 10 smallest integers in the array.
I've heard its called sorting but im not sure what needs to be done.
-
There's this handy button called "search" which will find your answer if you type in some appropriate word.
-
maybe use qsort() to sort the numbers first in ascending order, then grab the first 10 elements of the sorted array.
-
There are several ways of sorting arrays..
I'll post one here, so you'll have an idea:
Code:
#include <stdio.h>
#define MAX 10
int main(void)
{
int array[MAX] = {2, 3, 4, 1, 7, 8, 9, 6, 0, 5};
int backup;
int sorted = 0; /*0 = false, 1 = true, if array is sorted -> sorted = true */
int i;
// compare array[i] to array[i + 1], if array[i] > array[i + 1], switch them
while(!sorted) {
sorted = 1;
for (i = 0; i < MAX - 1; i++)
if (array[i] > array[i + 1]) { /* switching values */
backup = array[i];
array[i] = array[i + 1];
array[i + 1] = backup;
sorted = 0;
}
}
for(i = 0; i < MAX; i++)
printf("%d\n", array[i]);
return 0;
}
-
You could try for example Google to search for "sorting algorithms". It would lead you to sites like this: http://www.concentric.net/~ttwang/sort/sort.htm