1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| #include<stdio.h> #include<malloc.h> void insertionsort(int *a, int N); int SelectAlg(int *A, int low, int high, int k);
int main() { int N,k,i; int *A; A = (int*)malloc(N * sizeof(int)); printf("Please input the number of the array:"); scanf("%d", &N); printf("Please input the list_number to find:"); scanf("%d", &k); printf("Please input the array:"); for(i=0; i<N; i++) scanf("%d",&A[i]); int k_num = SelectAlg(A, 0 , N-1 ,k); printf("%d", k_num); return 0;
}
int SelectAlg(int *A, int low, int high, int k) { int p = high - low + 1; if (p < 44) { insertionsort(A, p); return A[k-1]; }
int i,j; int **L; int q = p/5; L = (int **)malloc(q * sizeof(int*)); int *mid = (int *)malloc(q * sizeof(int)); int *A_one = (int *)malloc(p * sizeof(int)); int *A_two = (int *)malloc(p * sizeof(int)); int *A_three = (int *)malloc(p * sizeof(int)); int one = 0,two = 0,three = 0;
for (i = 0; i < q; ++i) { L[i] = (int *)malloc(5 * sizeof(int)); for (j = 0; j < 5; ++j) L[i][j] = A[(5*i)+j];
insertionsort(L[i], 5); mid[i] = L[i][2]; } for (i = 0; i < q; ++i) free(L[i]); free(L);
int mid_mid = SelectAlg(mid, 0, q-1, (q+1)/2);
for (i = 0; i < p; ++i) { if(A[i] < mid_mid) A_one[one++] = A[i];
else if(A[i] == mid_mid) A_two[two++] = A[i];
else if(A[i] > mid_mid) A_three[three++] = A[i]; }
if (one >= k) mid_mid = SelectAlg(A_one, 0, one-1, k); else if((one + two) < k) mid_mid = SelectAlg(A_three, 0, three-1, k-one-two);
free(mid); free(A_one); free(A_two); free(A_three);
return mid_mid; }
void insertionsort(int *a, int N){ int i = 1; int j,x; while (i<N){ int j = i; x = a[i]; while ((j>0)&&(a[j-1]>x)){ a[j] = a[j-1]; j = j -1; } a[j] = x; i = i+1; } }
|