Click here to Skip to main content
15,878,945 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have been trying for a long time and still could not figure out what is going wrong

There is no compiler error..
The Problem is that I CANT GET THE SORTED ARRAY

What I have tried:

C++
#include <iostream>
#include <string>
using namespace std;

int my_array(int _array[],int size )
{
    for(int i=0; i < size; i++)
    {
        return _array[i];
    }
}

swap(int i, int j, int k)
{
    i = j;
    i = k;
    k = j;
}

void sort(int _array[], int hole, int size)
{
    int i;
    hole = i;
    for (int hole = 1; hole < size; hole++)
    {
        if (hole > 0 && _array[hole-1] > _array[hole])
        {
            swap(_array[hole], i, _array[hole-1]);
            hole = hole - 1;
        }
    }
}

void sorted_array(int _array[], int hole, int size)
{
    sort(_array, hole, size);

}

int main()
{
    int _array[5];
    for (int i=0; i < 5; i++)
    {
        cout << "first element" << " " << i << " ";
        cin >> _array[i];
    }
    
    int hole;
    sorted_array(_array, hole, 5);
    cout << my_array(_array,5) << endl;
}
Posted
Updated 5-Jun-16 0:19am
v2

1 solution

Um...that's some odd code you have there!
Start with your first method:
C#
int my_array(int _array[],int size )
    {
    for(int i=0;i<size;i++)>
        {
        return _array[i];
        }
    }
It always returns the first element in the array, unless the size is negative, in which case it returns nothing at all. I'm surprised that compiles at all - it shouldn't on a modern compiler as there is a path such that the method does not return a value, and that is not allowed.
The second method:
C#
swap(int i,int j,int k)
    {
    i=j;
    i=k;
    k=j;
    }
Does nothing. Seriously, nothing at all. Values in C and C++ are passed by value, not by reference, which means that the function doesn't affect the world outside - the values inside the function are copies of the values outside, and any changes are not copied back. If they weren't, then you could call it like this:
C++
swap(1, 2, 3)
And then what would happen?
In addition that isn't a "swap" function, so quite what you expect it to do I'm not sure...
Start by looking at those two and working out what you actually meant to do, and try to get it working: use the debugger to help you. It's a wonderful tool that lets you see and control exactly what is happening while your code is running. Get to know it - it'll save you some serious head scratching later! And until you get them working, the rest of the code is pretty useless! When they work, you can use the debugger to work out what is wrong with the rest.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900