Solved

Sorting an Array

Posted on 2006-11-28
13
457 Views
Last Modified: 2013-12-14
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;
        }


0
Comment
Question by:mayan1
  • 4
  • 4
  • 3
  • +1
13 Comments
 

Author Comment

by:mayan1
ID: 18030058
In addition could you please comment the code so that I know what it is doing?
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 18031254
>>>>  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
 

Author Comment

by:mayan1
ID: 18033831
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
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 18034075
>> 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
 
LVL 12

Expert Comment

by:rajeev_devin
ID: 18034083

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
 
LVL 4

Expert Comment

by:Raymun
ID: 18034142
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:mayan1
ID: 18035695
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
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 18036188
>>>> 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
 

Author Comment

by:mayan1
ID: 18038656
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
 
LVL 4

Expert Comment

by:Raymun
ID: 18038750
selection_sort( array, array.size() );

instead of

sort(array.begin(), array.end());
0
 
LVL 4

Expert Comment

by:Raymun
ID: 18038762
and put all the function definitions before int main() instead of inside it
0
 
LVL 4

Accepted Solution

by:
Raymun earned 200 total points
ID: 18038794
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
 
LVL 39

Assisted Solution

by:itsmeandnobodyelse
itsmeandnobodyelse earned 300 total points
ID: 18039085
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

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
Jaspersoft Studio is a plugin for Eclipse that lets you create reports from a datasource.  In this article, we'll go over creating a report from a default template and setting up a datasource that connects to your database.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now