Sorting an Array

Hello, I am currently playing around in Dev C++ and would like to know how to I would like to create a function that is called from my main function that allows the user to enter 5 integers.   Once the integers are entered it should print the array out to the console.  

After printing the array in the order the integers were entered I should call a function to sort the array and then for a second time print the array, which now should display the integers in ascending sorted order.

I want to use this to sort my array if possible:

   void selection_sort(int a[], int length)
        {
               for (int count = 0 ; count < length - 1 ; count++)
                       swap(a[count],a[minimum_from(a,count,length)]);
        }
       
        int minimum_from(int a[], int position, int length)
        {
               int min_index = position;
       
               for (int count = position + 1 ; count < length ; count
++)
                       if (a[count] < a[min_index])
                               min_index = count;
                       return min_index;
        }
       
        void swap(int& first, int& second)
        {
               int temp = first;
               first = second;
               second = temp;
        }


mayan1Asked:
Who is Participating?
 
RaymunCommented:
structure should look similar to this:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

void swap...
void minimum_from...
void selection_sort...

int main()...
0
 
mayan1Author Commented:
In addition could you please comment the code so that I know what it is doing?
0
 
itsmeandnobodyelseCommented:
>>>>  I am currently playing around in Dev C++

Actually, the requirements are typical for homework. Here in EE we can't help if there isn't at least an attempt to solve the problem by the asker himself. The posted sort functions cannot be honoured as they are not self-written but copied from somewhere.

Please post code written by yourself. You may start by using the following:

// arraysort.cpp
#include <iostream>
#include <string>
using namespace std;


int main()
{
    // put here code to prompt for 5 integers

    // put here code to sort the array entered

    // put here code to print the sorted array

    return 0;
}


Regards, Alex

0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
mayan1Author Commented:
Sorry for the wrong information being attached please disregard that I was not trying to post anyone elses code.

Here is my code thus far I am lost:

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


int main()
{
                cout << "Enter 5 INTEGERS ONLY \n";
                        for (int a=0; a<5; a++)
                        cin >> array[a];
                cout << endl;

    sort(a, a+5);
   
    for (int i=0; i<5; i++)
        cout << a[i] << " ";


 

    return 0;
}
0
 
rajeev_devinCommented:
>> array[a];
What is the type of array.
To able to use the std::sort function in C++ you need to use containers.

It should be something like.

vector<int> array;
array.resize(5);

Then sort can be called this way:

sort(array.begin(), array.end());

Rest of you code is fine.
0
 
rajeev_devinCommented:

int main()
{
               vector<int> array;
      array.resize(5);
      
                cout << "Enter 5 INTEGERS ONLY \n";
                        for (int a=0; a<5; a++)
                        cin >> array[a];
                cout << endl;

    //sort(a, a+5); This will raise compilation error.
   sort(array.begin(), array.end()); // This is correct.
   
    for (int i=0; i<5; i++)
        cout << a[i] << " ";


 

    return 0;
}
0
 
RaymunCommented:
Hello,

Put all the code in the question in between "using namespace std" and "int main()". Keep in mind that a function cannot call another function unless it has already been defined. For example, your call to sort(a, a + 5) needs a definition for sort and it needs to be placed before main() and not after it. Once you've got it compiled, you can start off by calling each function and figure out what they do:

int array[5];  

// place cin cout stuff here

int iNum1 = 1, iNum2 = 2, iResult;

selection_sort( array, 5 );
swap( iNum1, iNum2 );
iResult = minimum_from( array, iNum1, iNum2 );

-Ray
0
 
mayan1Author Commented:
I am getting the following errors:
Compiler: Default compiler
Building Makefile: "C:\Dev-Cpp\Makefile.win"
Executing  make...
make.exe -f "C:\Dev-Cpp\Makefile.win" all
g++.exe -c SortArray.cpp -o SortArray.o -I"C:/Dev-Cpp/lib/gcc/mingw32/3.4.2/include"  -I"C:/Dev-Cpp/include/c++/3.4.2/backward"  -I"C:/Dev-Cpp/include/c++/3.4.2/mingw32"  -I"C:/Dev-Cpp/include/c++/3.4.2"  -I"C:/Dev-Cpp/include"  

SortArray.cpp: In function `int main()':
SortArray.cpp:8: error: `vector' undeclared (first use this function)
SortArray.cpp:8: error: (Each undeclared identifier is reported only once for each function it appears in.)
SortArray.cpp:8: error: expected primary-expression before "int"

SortArray.cpp:8: error: expected `;' before "int"
SortArray.cpp:9: error: `array' undeclared (first use this function)
SortArray.cpp:19: error: name lookup of `a' changed for new ISO `for' scoping
SortArray.cpp:12: error:   using obsolete binding at `a'
SortArray.cpp:19: error: invalid types `int[int]' for array subscript

make.exe: *** [SortArray.o] Error 1

Execution terminated

What did  I do wrong?

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


int main()
{
     vector<int> array;
     array.resize(5);
     
                cout << "Enter 5 INTEGERS ONLY \n";
                        for (int a=0; a<5; a++)
                        cin >> array[a];
                cout << endl;
 
   sort(array.begin(), array.end()); // This is correct.
   
    for (int i=0; i<5; i++)
        cout << a[i] << " ";


 

    return 0;
}
0
 
itsmeandnobodyelseCommented:
>>>> SortArray.cpp:8: error: `vector' undeclared (first use this function)

You need to include std::vector template class

#include <vector>


Note if using std::vector you need to change the sort functions posted above by

   void selection_sort(std::vector<int>& a, int length)
        {
               for (int count = 0 ; count < length - 1 ; count++)
                       swap(a[count],a[minimum_from(a,count,length)]);
        }
       
        int minimum_from(std::vector<int>& a, int position, int length)
        {
               int min_index = position;
       
               for (int count = position + 1 ; count < length ; ++count)
                       if (a[count] < a[min_index])
                               min_index = count;
                       return min_index;
        }
       
        void swap(int& first, int& second)
        {
               int temp = first;
               first = second;
               second = temp;
        }

FYI: std::vector is a template class from STL (standard template library) which is part of C++ standard since 1996. It is supposed to fully replace old C arrays where you have to care for allocation and bounds checking yourself. So,

   int a[5] = { 0 };  

would turn to

   std::vector<int> a(5, 0);

Note, you can omit std:: prefix by using the statement  

   using namespace std;

However that never should be done in the header files but in the cpp files only.

Regards, Alex






0
 
mayan1Author Commented:
I am still having a hard time understanding.  Here is my code:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int array[5];


int main()
{
     vector<int> array;
     array.resize(5);
     
                cout << "Enter 5 INTEGERS ONLY \n";
                        for (int a=0; a<5; a++)
                        cin >> array[a];
                cout << endl;
 
   sort(array.begin(), array.end());
   
    for (int i=0; i<5; i++)
        cout << a[i] << " ";


void selection_sort(std::vector<int>& a, int length)
        {
               for (int count = 0 ; count < length - 1 ; count++)
                       swap(a[count],a[minimum_from(a,count,length)]);
        }
       
        int minimum_from(std::vector<int>& a, int position, int length)
        {
               int min_index = position;
       
               for (int count = position + 1 ; count < length ; ++count)
                       if (a[count] < a[min_index])
                               min_index = count;
                       return min_index;
        }
       
        void swap(int& first, int& second)
        {
               int temp = first;
               first = second;
               second = temp;
        }


    return 0;
}
0
 
RaymunCommented:
selection_sort( array, array.size() );

instead of

sort(array.begin(), array.end());
0
 
RaymunCommented:
and put all the function definitions before int main() instead of inside it
0
 
itsmeandnobodyelseCommented:
To add to above information:

if you call a function selection_sort in function main, the function prototype must be known. So, you can do:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

// declare prototype
void selection_sort(std::vector<int>& a, int length);  


int main()
{
      ....

      // now you can call selection sort, cause the compiler knows about the function and its arguments
      selection_sort(array, array.size());

     return 0;
}

The function body can be defined below now or in another cpp file.

void selection_sort(std::vector<int>& a, int length)
{
     ...
}

Note, as selection_sort calls two other functions - minimum_from and swap - you have to *declare* these function prior to calling them:

...

int minimum_from(std::vector<int>& a, int position, int length);
void swap(int& first, int& second);

void selection_sort(std::vector<int>& a, int length)
{
    ...
     if (....     [minimum_from(...)] )
           swap(...);
}

You also could put the implementation of minimum_from, swap above the body of selection_sort and it will work as well. But working with prototypes is the better method.

So, the skeleton of your code is:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

// declare prototypes
void selection_sort(std::vector<int>& a, int length);  
int minimum_from(std::vector<int>& a, int position, int length);
void swap(int& first, int& second);

int main()
{
    ....
}

void selection_sort(std::vector<int>& a, int length)
{
    ...
}

int minimum_from(std::vector<int>& a, int position, int length)
{
    ...
}

void swap(int& first, int& second)
{
     ...
}

>>>> swap

'swap' isn't a good name cause STL (standard template library) has a swap function as well. You didn't get problems till now cause you didn't include <algorithm> where the swap function was defined. Actually both function do the same but it will not compile if you have two global functions using the same name. The easiest way out is to rename your swap function to swap_ints or selection_swap.

>>>> void selection_sort(std::vector<int>& a, int length)

The length argument is redundant when using std::vector cause you can get the 'length' by calling array.size(). I would suggest to change the functions selection_sort and minimum_from accordingly:

    void selection_sort(std::vector<int>& a)
    {
         int length = a.size();
         // the rest doesn't change
        ...
    }

Note, you need to remove the length argument from the prototypes as well and the call of selection_sort turns to:

int main()
{
      ...
      selection_sort(array);
      ...
}
     
Regards, Alex

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.