-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquick.c
More file actions
68 lines (59 loc) · 952 Bytes
/
quick.c
File metadata and controls
68 lines (59 loc) · 952 Bytes
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
#include<stdio.h>
void swap( int *, int * );
void Quicksort(int [], int , int );
int main()
{
int n;
scanf("%d",&n);
int A[n];
for(int i = 0; i<n ;i++)
scanf("%d ",&A[i]);
//Quicksort(A,0,n-1);
printf(" \n %d",kthLargest(A,0,n-1,2));
//for(int i =0; i<n;i++)
// printf("%d ",A[i]);
}
int kthLargest(int A[], int l, int r, int k)
{
if(k>0 && k<=r-l+1)
{
int p = partition(A,l,r);
if(p-1 == k)
return A[p];
else if(p-1>k-1)
return kthLargest(A,l,p-1,k);
else
return kthLargest(A,p+1,r,k-p+l-1);
}
}
void Quicksort(int A[],int l, int r)
{
int p;
if(l<r)
{
p = partition(A,l,r);
Quicksort(A,l,p-1);
Quicksort(A,p+1,r);
}
}
int partition(int A[], int left, int right)
{
int i = (left - 1);
int p = A[right];
for(int j = left; j<right; j++)
{
if(A[j] < p)
{
i++;
swap(&A[i],&A[j]);
}
}
swap(&A[i+1],p);
return i+1;
}
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}