-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSort.cpp
More file actions
67 lines (59 loc) · 1.66 KB
/
Copy pathSelectionSort.cpp
File metadata and controls
67 lines (59 loc) · 1.66 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
/* SELECTION SORT */
#include <iostream>
using namespace std;
// function to swap minimum element to its right index
void swap(int *a, int *b) {
// swapping of elements
int temp = *a;
*a = *b;
*b = temp;
}
// function to display array
void display(int array[], int size) {
// printing array
for (int i = 0; i < size; i++) {
cout << " " << array[i];
}
cout << endl;
}
// Selection sort algorithm function
void selectionSort(int array[], int size) {
/* outer loop will run n-1 times because last element
will be in sorted array automatically */
for (int i = 0; i < size - 1; i++) {
// current index which stores minimum value of element
int minIndex = i;
// loop to compare elements
for (int j = i + 1; j < size; j++) {
/* to sort in descending order chane > to < */
// finding the minimum element
if (array[j] < array[minIndex]) {
// assigning minimum index
minIndex = j;
}
}
// function to swap minimum element to its right index
swap(&array[minIndex], &array[i]);
}
}
// main function
int main() {
// array of size 20
int array[20];
// size of array
int size;
cout << "Enter the size of array: ";
cin >> size;
// array of size user entered
array[size];
// input array elements at each index
cout << "Enter array elements\n";
for (int i = 0; i < size; i++) {
cout << "\tEnter array element at " << i << "th index: ";
cin >> array[i];
}
cout << "Sorted Array: ";
selectionSort(array, size);
display(array, size);
return 0;
}