Repository navigation
Expand file tree
/
Copy pathcountsort.cpp
More file actions
104 lines (86 loc) · 1.45 KB
/
Copy pathcountsort.cpp
File metadata and controls
104 lines (86 loc) · 1.45 KB
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
102
103
104
// CountingSort.cpp : Defines the entry point for the console application.
//
#include <iostream>
int A[] = {13, 19, 9, 5, 12, 8, 7, 4, 11, 2, 6, 21};
int len = sizeof(A)/sizeof(A[0]);
int B[12];
int C[21];
int K = 21;
void countingSort()
{
memset(C,0,sizeof(C));
for(int i=0;i<len;i++)
{
C[A[i]] += 1;
}
for(int i=1; i<K; i++)
{
C[i] += C[i-1];
}
for(int i=len-1; i>=0; i--)
{
B[C[A[i]-1]] = A[i];
C[A[i]-1] -= 1;
}
}
int partition(int p, int r)
{
int i = p - 1;
int j = r + 1;
int x = A[p];
while(1)
{
do
{
j--;
} while(A[j] > x);
do
{
i++;
} while(A[i] < x);
if(i < j)
{
int tmp = A[j];
A[j] = A[i];
A[i] = tmp;
}
else
{
return j;
}
}
}
int randomizedPartition(int p, int r)
{
int len = r-p;
int i = rand()%len + p;
int tmp = A[i];
A[i] = A[p];
A[p] = tmp;
return partition(p, r);
}
int randomizedSelect(int p, int r, int i)
{
if(p == r)
{
return A[p];
}
int q = randomizedPartition(p, r);
int k = q - p + 1;
if(i<=k)
{
randomizedSelect(p,q,i);
}
else
{
randomizedSelect(q+1,r,i-k);
}
}
#if 0
int _tmain(int argc, _TCHAR* argv[])
{
// countingSort();
int x = randomizedSelect(0,12,3);
return 0;
}
#endif