This part of the content from HTTP://WWW.CNBLOGS.COM/MINGC, the author is only used to organize learning.
Problem Description: Write a program to solve the selection problem. Make K=N/2. Draw a table showing how long your program will run when n is a different value.
Understanding: There is a set of n number to determine the largest of the K, called the Choice Problem (selection problem)
Idea: Read the pre-K number to the TEMP array tmp (and sort in descending order). Then read the subsequent number x one by one, and when X is greater than the number of K, add it to the array tmp (and in descending order). Finally returns the value on the position k-1
#include <stdio.h> #include <stdlib.h> #include <time.h> #define N 100int Select (int* arr, int N, int k); v OID Main () {int I, value;int* arr;clock_t Elapse;srand ((unsigned) time (NULL)), arr = (int*) malloc (sizeof (int) * N); for (i = 0 ; i < N; i++) {Arr[i] = rand ()% 1000; The resulting random number limit is within 1000 printf ("%d", Arr[i]);} printf ("\ n"); elapse = clock (); value = Select (Arr, n, n/2); elapse = Clock ()-elapse;printf ("Value:%d, elapsed:%.4lfs\n", Value, (double) elapse/1000); System ("Pause");} int Select (int* arr, int n, int k) {int i, j, t;int* tmp;tmp = (int *) malloc (sizeof (int) * k); for (i = 0; i < K; i++) Read k elements and arrange in ascending order {Tmp[i] = arr[i];for (j = i; j > 0; j--) {if (Tmp[j] < tmp[j-1]) {t = tmp[j];tmp[j] = tmp[j-1];tmp[ J-1] = t;}}} printf ("reads k elements and arranges in ascending order: \ n"); for (i = 0; i < K; i++) {printf ("%d", Tmp[i]);} printf ("\ n"); for (i = k; i<n; i++)//Add new elements and arrange in ascending order {if (Arr[i] > Tmp[0]) {tmp[0] = arr[i];for (j = 0; J < K-1; J + +) {if (Tmp[j] > Tmp[j+1]) {t = tmp[j];tmp[j] = TMP[j+1];tmp[j+1] = t;}}} printf ("Add new elements and arrange in ascending order: \ n"); for (i = 0; i < K; i++) {printf ("%d", Tmp[i]);} printf ("\ n"); return tmp[k-1];}
Notes:
1.srand ((unsigned) time (NULL));
Initializes the seed of the random function. Srand ((unsigned) time (NULL)); is to take system times as seed, because time is changed, the seed changes, can produce different random numbers.
When used, the parameters can be arbitrary data of type unsigned, such as Srand (10).
If you do not use Srand (), the random number generated with Rand () may be the same.
2.int* arr;
arr = (int*) malloc (sizeof (int) * N);
When you use a pointer to point to a string, you must create dynamic space for it, otherwise when you assign a value, the error is prompted because there is no space allocated.
You can also use int arr[maxsize] to directly define the array space.
"Data structure and algorithm analysis--c language description" Practice 1.1--selection problem