-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselection.c
More file actions
82 lines (65 loc) · 1.34 KB
/
selection.c
File metadata and controls
82 lines (65 loc) · 1.34 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
//Select Kth element from unsorted array
//O(n) algorithm : 2 functions
//Select with partition
/**
Quicksort(A, p, q)
if p < q then
next_pivot ← Partition(A, p, q)
Quicksort(A, p, next_pivot − 1)
Quicksort(A, next_pivot + 1, q)
end if
The following code partitions A[p..q] around A[q]
Partition(A, p, q)
x ← A[q]
next_pivot ← p − 1
for j ← p to q do
if A[j] ≤ x then
swap A[i + 1] and A[j]
next_pivot ← next_pivot +1
end if
end for
return i
**/
#include<stdio.h>
void do_swap(int *a,int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int a[],int start,int end) {
int x = a[end];
int next_pivot = start - 1;
int i;
for (i = start;i<=end;i++) {
if(a[i] <= x) {
do_swap(&a[next_pivot+1],&a[i]);
next_pivot = next_pivot + 1;
}
}
return next_pivot;
}
int select(int a[],int start,int end,int k) {
int next_pivot;
while(start <=end ) {
next_pivot = partition(a,start,end);
if(k == next_pivot) {
return 1;
}else if(k < next_pivot) {
end = next_pivot - 1; // as pivot is at right position do not consider pivot again
}else {
start = next_pivot + 1;
}
}
return -1;
}
int main() {
int k = 4;
int result;
int a [] = {20,8,12,2,5,40};
result = select(a,0,5,k);
if(1 == result) {
printf("\n element found %d\n",a[k]);
}else {
printf("\n element not fount \n");
}
}