-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindkminimumelements.cpp
More file actions
56 lines (51 loc) · 1.05 KB
/
Copy pathfindkminimumelements.cpp
File metadata and controls
56 lines (51 loc) · 1.05 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
#include<iostream>
#include<stdlib.h>
using namespace std;
void swap(int &a,int &b){
int temp=a;
a=b;
b=temp;
}
int partition(int arr[],int low,int high){
int left,right,pivot;
int r=low+(rand()%(high-low+1));
swap(arr[r],arr[low]);
pivot=arr[low];
left=low;
right=high;
/*very imp: dont confuse between low,high and left,right
for traversing and swapping you need left and right*/
while(left<right){
while(arr[left]<=pivot)
left++;
while(arr[right]>pivot)
right--;
if(left<right)
swap(arr[left],arr[right]);
}
arr[low]=arr[right];
arr[right]=pivot;
return right;
}
void quickselect(int arr[],int n,int k){
int low=0;
int high=n-1;
int index=partition(arr,low,high);
while(index!=k-1){
if(index>k-1){
high=index-1;
index=partition(arr,low,high);
}
else{
low=index+1;
index=partition(arr,low,high);
}
}
for(int i=0;i<k;i++)
cout<<arr[i]<<" ";
}
int main(){
int arr[]={34,1,2,89,56,23};
cout<<"Finding the minimum 2 elements...";
quickselect(arr,6,2);
}