-2

i have the following code

#include <iostream>

using namespace std;

int *sort(int arr[]){
    for(int i =0; i< 1; i++){
        for(int j= 1; j< 5; j++){

            if(arr[i]< arr[j]){
                int temp = arr[i];
                arr[i] =arr[j];
                arr[j] = temp;
            }

        }

    }
    for(int k=0; k<5;k++){
        cout<<arr[k];
    }
return arr;
}

int main(){  
    int arr[5] = {1,2,3,4,5};
    sort(arr);
    for(int m=0; m<5; m++){
        cout<<arr[m];
    }
}

my first problem is that how to pass array by value so that the original array does not change, and secondly the my sort function does not generate correct sorting i want to sort array in decreasing order.

Caleth
  • 52,200
  • 2
  • 44
  • 75
Hidayat ullah
  • 21
  • 2
  • 7

4 Answers4

1

In idiomatic C++, an array arr of 5 ints is declared std::array<int, 5> arr; or std::vector<int> arr(5);. Swapping of values is std::swap. Functions should either alter their parameters and return void, or alter a copy and return that value.

You also don't loop through every element in your outer loop.

#include <array>
#include <iostream>

void sort(std::array<int, 5> & arr){
    for(int i = 0; i < 5; i++){
        for(int j = 1; j < 5; j++){
            if(arr[i] < arr[j]){
                std::swap(arr[i], arr[j]);
            }
        }
    }
}

int main(){  
    std::array<int, 5> arr = {1,2,3,4,5};
    sort(arr);
    for(int m=0; m<5; m++){
        std::cout<<arr[m];
    }
}

However, the easiest way to sort is to use <algorithm>'s std::sort, which takes a range as two Iterator parameters

#include <algorithm>
#include <array>
#include <iostream>

int main(){  
    std::array<int, 5> arr = {1,2,3,4,5};
    std::sort(arr.begin(), arr.end(), std::greater<int>{});
    for(int m=0; m<5; m++){
        std::cout<<arr[m];
    }
}
Caleth
  • 52,200
  • 2
  • 44
  • 75
  • or just `std::sort(std::begin(arr), std::end(arr), std::greater{});`, which will work for *either* a native `int arr[N]` array or a `std::array`. – WhozCraig May 03 '18 at 10:26
  • @WhozCraig I don't want OP to have any excuse to use `int arr[N]`. It doesn't belong in modern C++ – Caleth May 03 '18 at 10:28
  • i also have tried the outer loop through < arraysize but it does produce the same result is the one above – Hidayat ullah May 03 '18 at 10:30
0

1) you can use c++ swap function instead using a temp variable

swap(arr[i], arr[j]);

2) your for loops should look like this

for(int i = 0; i < 5; i++) {
    for(int j = i; j < 5; j++) {

The outer loop has to iterate through the whole array (from 0 to 4) and the inner has to iterate through the 'right side' of the array, because the left side is already sorted

so we can't pass array by value

https://stackoverflow.com/a/16137997/6521788 https://stackoverflow.com/a/16137995/6521788

You can just copy the values into a new array

  • i am preparing for a university test for MS SE admission where built in method are not allowed to use and also they told me that if any question like sorting of array if it is given then you need to pass array by value. – Hidayat ullah May 03 '18 at 10:20
  • 1
    @Hidayatullah Whoever "they" are in your statement, *"they told me that if any question like sorting of array if it is given then you need to pass array by value. "* doesn't know wtf "they" are talking about regarding how native arrays are passed as arguments in C++ (or C). Either they're naive, they're pranking you, or you misunderstood their statement. – WhozCraig May 03 '18 at 10:22
  • @WhozCraig can we do pass by value in java or c because test is not restricted to c++ – Hidayat ullah May 03 '18 at 10:24
  • @Hidayatullah I already answered that question regarding both C and C++. For Java, [see here](https://stackoverflow.com/questions/12757841/are-arrays-passed-by-value-or-passed-by-reference-in-java). – WhozCraig May 03 '18 at 10:28
  • @WhozCraig this is the statement from university."Your function should not alter the input parameter(s) in any way. For example, if your function needs to sort an array input parameter, you must sort a copy of the parameter, since otherwise, the caller of the function will see the sorted version of the input parameter. For example, main() { int [ ] a = new int [ ] {4, 2, 5}; foo(a); // when program reaches here value of a will be {2, 4, 5} because an array is passed by reference! } void foo(int [ ] a) { // sort the array a into ascending order } – Hidayat ullah May 03 '18 at 10:51
  • None of the questions require you sort any input parameter. If you choose to do so please sort a copy or you will receive no credit for the question." – Hidayat ullah May 03 '18 at 10:51
  • @Hidayatullah Nowhere in that statement is the term "by value" ever even mentioned, so again, whomever said *that* to you didn't know what they were talking about. In fact, in the text you provided, it specifically states expectations, telling you *precisely* what to do: *"you must sort a copy of the parameter"*. Granted, the verbiage in their instructions is dreadful, but at least they state what to do. If all else fails you could actually ask the instructors and/or TAs. – WhozCraig May 03 '18 at 16:17
0

Basic answer: you cannot pass arrays by value in C++.

Solution 1: Make a copy of your C-style array before passing it to your function, and remove your return statement as it won't be needed.

Solution 2: Use std::array, which is a container which provides the same functionality as a basic array, and as a copy constructor and copy assignment operators.

Other remark: The STL does provide sort algorithms (std::sort), so in your future programmer's life do not implement sorting algorithms yourself, unless you do something really specific where performance matters.

op414
  • 582
  • 5
  • 15
0

your question indicates that there might be quite a bit of confusion as to how one deals with pointers in C++. If my assumption is incorrect then just skip ahead(i will provide "my solution"/correction at the end of this post).

To answer your first question: you can't pass C-style arrays per value in C++, nor by reference for that matter. Your only "option" would be looping through the pointer until '\n' is reached & store the contents in a new array created in your function.

which would be something along the lines of

'{
    int arrx[5] = {};

    for(int i = 0; i < 5; i++) 
    {
        arrx[i] = arr[i];
    }
    for (int j = 0; j < 5; j++) // print
    {
        std::cout << arrx[j];
    }
    return 0;
}`

A couple of other things about pointers:

int *sort(int arr[]){ -> arr[] passes a pointer to arr(same as *arr)

Pointer point to the first element in the memory pointed to & have no inherit size meaning

sizeof(arr) / sizeof(arr[0])

would not work inside your sort function(which could lead to problems if you dont know exactly how long the array you want to search is). a simple solution would be to pass the size of your array by value/reference to your function. Another solution would be to loop through the array itself via something akin to

for(;arr != '\n'; arr++)
{
//your code here

You can get a lot more information about pointers than i could ever give you by visiting the various tutorial sites out there. for example: https://www.tutorialspoint.com/cplusplus/cpp_pointers.htm

http://www.cplusplus.com/doc/tutorial/pointers/

But now back to your original question and hopefully an answer to it.

int *sort(int arr[]) {
    for (int i = 0; i< 1; i++) { 

should be corrected to for(int i=0; i< 5-1; i++)

the sorting function you are trying to implement is called bubblesort. for further information & how exactly bubblesort works please refer to https://de.wikipedia.org/wiki/Bubblesort

        for (int j = 1; j< 5; j++) {

should be corrected to for(int i=0; i< 5-1-i; i++) because the last elements are already in place.

        if (arr[i]< arr[j]) {

should be corrected to if (arr[j]< arr[j+1]) because you want to compare(for example) the first element & the next element to get it in descending/ascending order. this gets done for every number pair in your array.

and finally:

        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;

should look something along the lines of:

        int temp = arr[j+1];
        arr[j+1] = arr[j];
        arr[j] = temp;

please note that you can also reformat it to:

        int temp = arr[j];
        arr[j] = arr[j+1];
        arr[j+1] = temp; // same output

as an example: if arr[j] = 5 and arr[j+1] = 6 then you store the value j+1(6) in temp, overwrite arr[j+1] with j(5) and lastly store 6 at j to get descending order(hope i got that right now, but you get the gist)

lastly; as others have correctly pointed out already, you can use std::swap instead of using key/temp variables.

way
  • 1
  • 1