D
D
Demigodd2018-04-10 09:34:08
C++ / C#
Demigodd, 2018-04-10 09:34:08

How to pass an array to a function and return the original array after sorting?

spoiler
#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";
}

I can’t figure out how to make the array local and after sorting it disappears, and every time this array is used again in main. The output was the initial generated array.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivanq, 2018-04-10
@Demigodd

First, you don't need to separate PrintArrayand SourceArray. They have the same code.
Secondly, the array is passed to BubbleSortby pointer, that is, if BubbleSortthe 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 question

Ask a Question

731 491 924 answers to any question