Repository navigation
Expand file tree
/
Copy patharrayFuncs.cpp
More file actions
executable file
·86 lines (68 loc) · 1.92 KB
/
Copy patharrayFuncs.cpp
File metadata and controls
executable file
·86 lines (68 loc) · 1.92 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
#include <cassert>
#include "arrayFuncs.h"
#include <sstream> // for ostringstream
// intToString converts an int to a string
std::string intToString(int i) {
// creates a stream like cout, cerr that writes to a string
std::ostringstream oss;
oss << i;
return oss.str(); // return the string result
}
// arrayToString converts an int array to a string
std::string arrayToString(int a[], int size) {
if (size==0)
return "{}";
std::ostringstream oss;
// fencepost problem; first element gets no comma in front
oss << "{" + intToString(a[0]);
for (int i=1; i<size; i++) {
oss << "," << intToString(a[i]);
}
oss << "}";
return oss.str();
}
// indexOfMax
// a: an array of ints n: how many ints in array
// Return the index of largest value.
// If more than one element has largest value,
// break tie by returning the smallest index that
// corresponds to an element with the largest value.
// You may assume size >= 1
int indexOfMax(int *a, int n) {
assert(n >= 1);
int maxIdx = 0;
for (int i = 1; i < n; i++) {
if (a[i] > a[maxIdx]) {
maxIdx = i;
}
}
return maxIdx;
}
// indexOfMin
// a: an array of ints n: how many ints in array
// Return the index of smallest value.
// If more than one element has smallest value,
// break tie by returning the smallest index that
// corresponds to an element with the smallest value.
// You may assume size >= 1
int indexOfMin(int *a, int n) {
assert(n >= 1);
int minIdx = 0;
for (int i = 1; i < n; i++) {
if (a[i] < a[minIdx]) {
minIdx = i;
}
}
return minIdx;
}
// swap
// a: an array of ints. n: how many ints in array
// swap the values of a[i] and a[j]
void swap(int *a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
// save the old value of a[i] in a variable
// make new value of a[i] be the old value of a[j]
// make new value of a[j] be the old saved value of a[i]
}