Answer the question
In order to leave comments, you need to log in
How to pass an array to a function and return the original array after sorting?
#include <iostream>
#include <cstdlib>
#include <ctime>
void SourceArray(int* array, int n);
void PrintArray(int* array, int n);
void BubbleSort(int array[], int size) {
for(int i = 1; i < size; ++i)
{
for(int r = 0; r < size - i; r++)
{
if(array[r] > array[r + 1])
{
int temp = array[r];
array[r] = array[r + 1];
array[r + 1] = temp;
}
}
}
std::cout << "Bubble Sorted Array1: ";
PrintArray(array, size);
}
int main() {
srand(time(NULL));
int size;
std::cout << "Array Size: ";
std::cin >> size;
int array[size];
//Создаем Массив с рандомными элементами
for(int i = 0; i < size; ++i)
{
array[i] = (rand() % 100) + 1;
}
std::cout << "Source Array: ";
SourceArray(array, size);
//Передаем Массив в Функцию
BubbleSort(array, size);
//Как сделать, что бы тут был исходный массив, а не сортированный ?
PrintArray(array, size);
return 0;
}
void SourceArray(int* array, int n) {
for(int i = 0; i < n; ++i) {
std::cout << array[i] << " ";
}
std::cout << "\n\n";
}
void PrintArray(int* array, int n) {
for(int i = 0; i < n; ++i) {
std::cout << array[i] << " ";
}
std::cout << "\n";
}
Answer the question
In order to leave comments, you need to log in
First, you don't need to separate PrintArray
and SourceArray
. They have the same code.
Secondly, the array is passed to BubbleSort
by pointer, that is, if BubbleSort
the array changes, then it changes at all.
You need to copy the array before the call BubbleSort
, and pass the copy to the function. For example:
int array_copy[size];
memcpy(array_copy, array, size);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question