0

I have a problem, I try to sort tabs and display them. User inputs number of how many tabs he wants to sort, but the last tab is not displayed.

I am beginner. How can I find where I made an error?

I tried tracking n integer, it resets to 0 after sorting the last tab, probably sorting algorithm messes it up, but I don't know how.

#include<iostream>
using namespace std;

void bsort(int tab[]) {
    for(int i=0; i<sizeof(tab)-1; i++) {
        for(int j=0; j<sizeof(tab)-1; j++) {
            if(tab[j] < tab[j+1]) swap(tab[j+1], tab[j]);
        }
    }
}

int main() {
    int t, n;
    cin >> t;
    for(int i=0; i<t; i++) {

        cin >> n;
        int tab[n];

        for(int j=0; j<n; j++) {
            cin >> tab[j];
        }

        bsort(tab);
        cout << n << endl;
        for(int k=0; k<n; k++) {
            cout << tab[k] << " ";
        }
    }
    return 0;
}
halfer
  • 19,824
  • 17
  • 99
  • 186
jikix
  • 39
  • 1
  • 5
  • 2
    `for(int i=0; i – PaulMcKenzie Feb 06 '20 at 20:38
  • 2
    `cin >> n; int tab[n];` is not standard c++, [read here](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard), better use `std::vector` – 463035818_is_not_an_ai Feb 06 '20 at 20:39
  • 2
    Why are you writing your own sorting function? What's wrong with `std::sort`? – Jesper Juhl Feb 06 '20 at 20:39
  • 1
    Does this answer your question? [When a function has a specific-size array parameter, why is it replaced with a pointer?](https://stackoverflow.com/questions/1328223/when-a-function-has-a-specific-size-array-parameter-why-is-it-replaced-with-a-p) – scohe001 Feb 06 '20 at 20:42

1 Answers1

1

Arrays are always passed by pointer to functions and the "length" of that array is lost. sizeof on an array parameter of the function will always return the size of a pointer (4 or 8 depending if your app is 32-bit or 64-bit).

Instead of this:

void bsort(int tab[]) {

This (with a few additional fixes and optimizations thrown in):

void bsort(int* tab, int length) {
    for(int i=0; i<length; i++) {
        for(int j=i+1; j<length; j++) { 
            if(tab[i] > tab[j]) {        // replace "<" with ">" if you want descending sort
               int temp = tab[i];
               tab[i] = tab[j];
               tab[j] = tab[i];
            }
        }
    }
}

Then, in your main function, invoke with the length of that array;

bsort(tab, n);

Also, I suspect there are other optimizations you can make to your bsort function.

selbie
  • 100,020
  • 15
  • 103
  • 173