Title: 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.
(There is a set of n number to determine the largest of the K, called the selection 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.
Realize:
1#include <stdio.h>2#include <stdlib.h>3#include <time.h>4 5 #defineN 100006 7 int Select(intArr[],intNintk);8 9 intMainvoid)Ten { One int*arr; A intvalue; - clock_t elapse; - theSystem"Color 0A"); - - Srand ((unsigned) time (NULL)); -Arr = (int*)malloc(sizeof(int) *N); + for(intj =0; J < N; J + +) - { +ARR[J] = rand ()%100000; Aprintf"%d", Arr[j]); at } -Putchar ('\ n'); - -Elapse =clock (); -Value =Select(arr, n, N/2); -elapse = Clock ()-elapse; inprintf"Value:%d, elapsed:%.4lfs\n", Value, (Double) Elapse/ +); - to Free(arr); +System"Pause"); - return 0; the } * $ /*Select the k largest in the array*/Panax Notoginseng int Select(intArr[],intNintk) - { the int*tmp; + intI, J, ret; A theTMP = (int*)malloc(sizeof(int) *k); +tmp[0] = arr[0]; - for(i =1; I < K; i++)//read k elements and sort in descending order $ { $Tmp[i] =Arr[i]; - for(j = i; j >0; j--) - { the if(Arr[i] > Tmp[j-1]) - {WuyiTMP[J] = tmp[j-1]; theTmp[j-1] =Arr[i]; - } Wu } - } About $ for(i = k; i < n; i++)//read in arr[k] - { - if(Tmp[k-1] <Arr[i]) - { ATmp[k-1] =Arr[i]; + for(j = k-1; J >0; j--) the { - if(Arr[i] > Tmp[j-1]) $ { theTMP[J] = tmp[j-1]; theTmp[j-1] =Arr[i]; the } the } - } in } the theret = tmp[k-1]; About Free(TMP); the returnret; the}
Recording:
N Value |
Time-consuming (seconds) |
10000 |
0.0820 |
20000 |
0.3260 |
30000 |
0.7320 |
40000 |
1.3080 |
50000 |
2.0320 |
60000 |
2.9390 |
70000 |
3.9990 |
80000 |
5.2160 |
90000 |
6.6530 |
100000 |
8.1610 |
Small note: The algorithm can give the result in a reasonable time when the input data is small. This algorithm is impractical if the amount of data is too large.
Data structure and algorithm analysis (C language description) Exercise 1.1