ordine crescente "senza" vettori in c++
Here's an example of how you can sort numbers in ascending order without using vectors in C++:
#include <iostream>
void sortNumbers(int arr[], int size) {
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int numbers[] = { 64, 25, 12, 22, 11 };
int size = sizeof(numbers) / sizeof(numbers[0]);
sortNumbers(numbers, size);
std::cout << "Sorted numbers in ascending order: ";
for (int i = 0; i < size; ++i) {
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
- sortNumbers
function implements the Bubble Sort algorithm to sort the array in ascending order.
- The main
function initializes an array of numbers.
- size
variable stores the size of the array.
- sortNumbers(numbers, size)
sorts the numbers using the sortNumbers
function.
- The sorted array is then printed using a for
loop within the main
function.