generated from Manchas2k4/tc1031-act12-search-sorting-algorithms-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselection.h
69 lines (63 loc) · 1.52 KB
/
selection.h
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
// =================================================================
//
// File: selection.h
// Author: Pedro Perez
// Description: This file contains the implementation of the
// bubble sort.
//
// Copyright (c) 2020 by Tecnologico de Monterrey.
// All Rights Reserved. May be reproduced for any non-commercial
// purpose.
// =================================================================
#ifndef SELECTION_H
#define SELECTION_H
#include "header.h"
#include <vector>
// =================================================================
// Performs the selection sort algorithm on an array.
//
// @param A, an array of T elements.
// @param size, the number of elements in the array.
// =================================================================
template <class T>
int selectionSort(T *arr, int size) {
int pos;
int c=0;
for(int i = size - 1; i > 0; i--){
pos = 0;
for(int j = 1; j <= i; j++){
if(arr[j] > arr[pos]){
pos = j;
}
}
if (pos != i){
c++;
swap(arr, i, pos);
}
}
return c;
}
// =================================================================
// Performs the selection sort algorithm on a vector.
//
// @param A, a vector of T elements.
// =================================================================
template <class T>
int selectionSort(std::vector<T> &v) {
int pos;
int c=0;
for(int i = v.size() - 1; i > 0; i--){
pos = 0;
for(int j = 1; j <= i; j++){
if(v[j] > v[pos]){
pos = j;
}
}
if (pos != i){
c++;
swap(v, i, pos);
}
}
return c;
}
#endif /* SELECTION_H */