-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsort_array.cpp
More file actions
57 lines (37 loc) · 1.12 KB
/
sort_array.cpp
File metadata and controls
57 lines (37 loc) · 1.12 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
#include <iostream>
// this function is the core of this program :D
template<class T>
void sortArray(T* arr, size_t length){
// for each element of the array...
for (; length > 0; length--, arr++) {
T maxValue = *arr;
T* swapVal = arr;
//find the largest remaining number
for (size_t i = 0; i < length; i++)
if (maxValue < *(arr + i))
maxValue = *(swapVal = arr + i);
// switch elements' locations in the array
T temp = *arr;
*arr = *swapVal;
*swapVal = temp;
}
}
int main(){
std::cout <<"How many numbers to sort?\n";
size_t length; // NOTE: size_t = unsigned long int
std::cin >>length;
// allocate some memory to hold our array
double userArray[length];
std::cout <<"Enter " <<length <<" numbers:\n";
for (size_t i = 0; i < length; i++)
std::cin >>userArray[i];
//sort the array
sortArray(userArray, length);
// print the array
std::cout <<"\nin numerical order:\n";
std::cout <<userArray[0];
for (size_t i = 1; i < length; i++)
std::cout <<", " <<userArray[i];
// terminating newlines are nice
std::cout <<std::endl;
}