-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkth_smallest.cpp
More file actions
72 lines (62 loc) · 1.46 KB
/
Copy pathkth_smallest.cpp
File metadata and controls
72 lines (62 loc) · 1.46 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
#include <iostream>
using namespace std;
void selectionSort(int arr[], int n);
void sort(int arr[], int n, int start);
void swap(int arr[], int a, int b);
int kthSmallest(int arr[], int n, int k);
bool isSorted(int arr[], int n);
void printArray(int arr[], int n);
int main() {
int arr[] = {3, 2, 11, 5, 1};
// 1 2 3 5 11
int smallest = kthSmallest(arr, 5, 2);
printArray(arr, 5);
cout << smallest << endl;
return 0;
}
int kthSmallest(int arr[], int n, int k)
{
// we will sort using selection sort as
// its time complexity is better than bubble sort
selectionSort(arr, n);
return arr[k-1];
}
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
if (isSorted(arr, n)) {
break;
}
sort(arr, n, i);
}
}
void sort(int arr[], int n, int start) {
int minimum = arr[start];
int minIndex = 0;
for (int i = start; i < n; i++) {
int ele = arr[i];
if (ele <= minimum) {
minimum = ele;
minIndex = i;
}
}
swap(arr, start, minIndex);
}
void swap(int arr[], int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
bool isSorted(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
if (arr[i] > arr[i+1]) {
return false;
}
}
return true;
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}