Repository navigation
Expand file tree
/
Copy path6_task.cpp
More file actions
89 lines (81 loc) · 1.91 KB
/
Copy path6_task.cpp
File metadata and controls
89 lines (81 loc) · 1.91 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
#include <iostream>
using namespace std;
// A utility function to swap two elements
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
/* This function takes last element as pivot, places
the pivot element at its correct position in sorted
array, and places all smaller (smaller than pivot)
to left of pivot and all greater elements to right
of pivot */
int partition (int arr[], int low, int high)
{
int ind=low+(rand()%(high-low));
swap(arr[ind],arr[high]);
int pivot = arr[high];
// pivot
int i = (high - 1);
for (int j = high-1; j >= low; j--)
{
//if current element is smaller than pivot, increment the low element
//swap elements at i and j
if (arr[j] <= pivot)
{
// increment index of smaller element
swap(&arr[i], &arr[j]);
i--;
}
}
swap(&arr[i +1], &arr[high]);
return (i + 1);
}
/* The main function that implements QuickSort
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
int quickSelect(int arr[], int low, int high,int *k)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
while (high > low) {
int i = partition(arr, low, high);
if (i > *k) high = i - 1;
else if (i < *k) low = i + 1;
else
return arr[i];
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver Code
int main()
{
int size=0;
cin>>size;
int *arr =new int [size];
int k=0;
cin>>k;
k=size-k-1;
int bufk = k;
for (int i = 0; i <size ; ++i) {
cin>>arr[i];
}
cout<<quickSort(arr, 0, size - 1,&k);
/*if (k==bufk)
{
k=arr[k];
}
cout<<k;
*/return 0;
}