Question

Sort in Ascending order then write to a file

Asked by: samkhool4u

hi!
iam trying to sort numbers form an array in ascending order.. and then writing them to a  file or on to a new array.
for e.g
 if i have an array of [ 5,6,2,7,4,3,54,133]
 i want to sort them in ascending order ...
any help will be appreciated
thankyou
           

 

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-06-12 at 10:14:07ID20646266
Topic

C++ Programming Language

Participating Experts
4
Points
60
Comments
10

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. DBGrid - TitleClick  :ascending,descending
    How do you make data ascending descending (sorted9 on dbgrid title click?
  2. SIMPLE ASCENDING SORT, EXIT,FLOAT..... NEWBIE
    i posted this question and i got replies which solved my problem... partly here is the link http://www.experts-exchange.com/Programming/Programming_Languages/Cplusplus/Q_20646266.html i am bringing this up because i deparately need a solution. thanks for all ur efforts.. ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: AssafLaviePosted on 2003-06-12 at 10:34:17ID: 8710924

use the standard algorithm std::sort, although I really recommend that you use vectors instead of arrays, this is c++ not c.
example:

#include <algorithm>
using namespace std;

int main()
{
    int v[5] = { 4, 3, 6, 4, 1 };
    std::sort(v, &v[4] + 1);
    return 0;
}

 

by: AssafLaviePosted on 2003-06-12 at 10:35:02ID: 8710931

the using statement isn't necessary if you use the std:: prefix - force of habbit..

 

by: samkhool4uPosted on 2003-06-12 at 13:40:12ID: 8712516

in your above program..
  are u assumimg that the array contains only these values {4,3,5,4,1}
  i mean if the array has some other data in it..  then will it be able to sort in ascending...?
   
  if u can could u please  make use of a lets say.. a simple for loop or a while loop or something/..
cause i have never used namespace std and  algorithm header. before..

also  
<<<<<   std::sort(v, &v[4] + 1);
  i dont quite understand what the above line does..   if u could kindly explain it to me.. i'd be greatful
 thank you

 

by: AssafLaviePosted on 2003-06-12 at 15:29:29ID: 8713120

The standard sort algorithm can sort anything that can be compared by the opeartor < in c++. It can also compare other stuff, for example user defined types, if you supply a comparing function for them.

To your question, no, I won't use a loop when the algorithm is already there implemented for me. Besides, I don't think the usage could be any simpler. So please take a look at the documentation about the std::sort algorithm and see what it does.
Usually it takes two paramteres: an iterator (or pointer) to the first element in the array you wish to sort and an iterator to the last one (actually, the one after the last one). It sorts from 'begin' to 'end'.
So:
std::sort(v, &v[4] + 1)
tells the function to sort the array starting from the first element (v) upto the end of the array (which is &v[4]+1 in this example with a 5 element array).
See also this example of sort:
http://www.josuttis.com/libbook/algo/sort1.cpp.html

Again, I recommend that you use vectors instead of arrays: http://www.parashift.com/c++-faq-lite/containers-and-templates.html#faq-34.1

With a vector it would have been simpler:
std::sort(yourVector.begin(), yourVector.end())
Isn't that nicer?
Please take the time to learn about the standard containers and algorithms - it's good for you. ;)

 

by: EarthQuakerPosted on 2003-06-12 at 19:06:55ID: 8714157

Just to mention sort(v, &v[4] + 1) could be more easily written like :

sort(v, v + 5);

 

by: reborn_assassinPosted on 2003-06-12 at 22:30:30ID: 8714979

// Author: Reborn Assassin
// Name:   Sort Program

#include "iostream.h"

void main()
{
      char ans = 'y';
while (ans =='y')
{
      int n[10], tp, x, y, total;
      total =  sizeof(n)/4; // Meaning you can change the size of the array
      for (x=1; x<=total; x++)
      {
            cout << "\nEnter number " << x << ": ";
            cin >> n[x];
      }
      for (x=1; x<=total-1; x++)
      {
            for (y=x+1; y<=total; y++)
            {
                  if (n[x] > n[y])
                  {
                        tp = n[x];
                        n[x] = n[y];
                        n[y] = tp;
                  }
            }
      }
      for (x=1; x<=total; x++)
              cout << endl << n[x];
      cin >> ans;
}
}

 

by: csridhar_76Posted on 2003-06-14 at 17:19:05ID: 8725270

here is a sample code using list.
i would prefer using list instead of vector as it has sort member func.


int main( )
{
   using namespace std;
   list <int> c1;
   list <int>::iterator c1_Iter;
   
   c1.push_back( 20 );
   c1.push_back( 10 );
   c1.push_back( 30 );

   cout << "Before sorting: c1 =";
   for ( c1_Iter = c1.begin( ); c1_Iter != c1.end( ); c1_Iter++ )
      cout << " " << *c1_Iter;
   cout << endl;

   c1.sort( );
   cout << "After sorting c1 =";
   for ( c1_Iter = c1.begin( ); c1_Iter != c1.end( ); c1_Iter++ )
      cout << " " << *c1_Iter;
   cout << endl;

   c1.sort( greater<int>( ) );
   cout << "After sorting with 'greater than' operation, c1 =";
   for ( c1_Iter = c1.begin( ); c1_Iter != c1.end( ); c1_Iter++ )
      cout << " " << *c1_Iter;
   cout << endl;
}

Output
Before sorting: c1 = 20 10 30
After sorting c1 = 10 20 30
After sorting with 'greater than' operation, c1 = 30 20 10

 

by: AssafLaviePosted on 2003-06-15 at 01:39:07ID: 8726357

>> i would prefer using list instead of vector as it has sort member func.

That's not a very good reason to prefer lists. They don't have random access so you aren't able to use faster sorts like binary on them.

 

by: samkhool4uPosted on 2003-06-15 at 03:40:16ID: 8726557

thanks for all ur efforts..
     
 i tried to impliment  reborn_assassin's program in to my program which is below
----------------------------------------------------------------------------------------------------------------------------------------------------------------

// AUTHOR--SAM
#include <iostream.h>
#include <fstream.h>

#include <conio.h>
//include <stdlib.h>



 fstream datafile;
 // declaring the file object so that it can communicate with the operating system

      int max=0,min=9999,i;
      float ave,sum2;
      long sum=0;
      int* contents;  // declares variable to read data from file
      char filename[16],words[80];
      double input;
      int keypress,anykey, count=0;

      void exit_prog()
      {
       cout<<"program terminated"<<endl;


      }
  //------------------- Welcom Screen Function-------------------//
      int welcome()
{
      gotoxy(15,5);
      cout<<"****************************************";
      gotoxy(15,6);
      cout<<"*\t\t   ------- COLLEGE\t     *";
      gotoxy(15,7);
      cout<<"*\t        FILE PROCESSING SYSTEM           *";
      gotoxy(15,8);
      cout<<"*\t\t PRESS C TO CONTINUE\t     *";
      gotoxy(15,9);
      cout<<"*                                      *";
      gotoxy(15,10);
      cout<<"****************************************";
      gotoxy(34,9);
      keypress=getche();
      stop:

return 0;
}
//----------------------Menu Screen Function----------------------//
int menu()
{  clrscr();
      gotoxy(15,5);
      cout<<"****************************************"<<endl;
      cout<<"\t      *\t\tFile Processing System\t     *"<<endl;
      cout<<"\t      *     \t  Please input option        *"<<endl;
      cout<<"\t      *                            \t     *"<<endl;
      cout<<"\t      * 1----------Create new data file      *"<<endl;
      cout<<"\t      * 2----------Input data to a file      *"<<endl;
      cout<<"\t      * 3----------View numbers form a file  *"<<endl;
      cout<<"\t      * 4----------Display maximum\t     *"<<endl;
      cout<<"\t      * 5----------Display minimum\t     *"<<endl;
      cout<<"\t      * 6----------Display total\t     *"<<endl;
      cout<<"\t      * 7----------Display the Average value *"<<endl;
      cout<<"\t      * 8----------Ascending sort \t     *"<<endl;
      cout<<"\t      * 9----------EXIT  \t\t     *"<<endl;
      cout<<"\t      *                            \t     *";
      gotoxy(15,18);
      cout<<"****************************************"<<endl;
      gotoxy(34,8);
      keypress=getche();

return 0;
}
//-------------OPTION 1 CREATE FILE---------------------------//
int create_file()
{
      // asking user to input name of the file to create
  cout<<"please enter the name of the file that you wish to create"<<endl;
  cout<<"use .txt as your file extension\n";

  cin>>filename;
  cout<<"\nA file named "<<filename<<" was created"<<endl;
  datafile.open(filename,ios::out);

  datafile.close(); // close file
return 0;
}


//-------------OPTION 2 INPUT DATA TO A FILE---------------------------//
int input_data()
 {

 // asking user to input name of the file to input data to
  cout<<"please enter the name of the file that you wish to input data to"<<endl;
  cout<<"please use the correct extension\n";

  cin>>filename;

       do
       {
            count++;
            datafile.open(filename,ios::app);
            clrscr();
            cout<<"input number";
            cin>>input;
            datafile<<input<<endl;
            datafile.close();
            cout<<("do you want to input another number... press anykey to continue or N to exit\n");

            keypress=getch();

            }while(keypress!=110&&keypress!=78);

            clrscr ();
            cout<<"You entered "<<count<<" numbers\n"<<endl;

return 0;

}
//-------------OPTION 3 VIEW DATA FORM A FILE---------------------------//
int view_file()
{

        // asking user to input name of the file from which the data needs to reviewed
  cout<<"please enter the name of the file which you wish to view the contents"<<endl;
  cout<<"please use the correct extension\n";
  cin>>filename;
      datafile.open(filename,ios::in);       // open numbers.txt file for reading

       while(!datafile.eof())  // keeps reading till the end of file
       {
            datafile.getline(words,80,'\n'); // read character by character form file ito words

            cout<<words<<endl;    // displays characters on the screen

       };

       datafile.close(); // close file
return 0;
};
//-------------OPTION 4 Maximum---------------------------//

int maximum()
{          contents= new int[count];
      datafile.open(filename,ios::in);       // opens numbers.txt file for reading
// displaying the contents of the file
      for(i=0;i<count;i++)  // keeps reading till the end of file
       {
            datafile>>contents[i]; // read character by character form file  ito words

            cout<<contents[i]<<endl;    // displays characters on the screen

       };

  // find and display max
      for(i=0;i<count;i++)
      {
                        if(contents[i]>max)
                              max=contents[i];
      }
      cout<<"max is "<<max<<"\n";

  datafile.close();
return 0;
}
//-------------OPTION 5 MINIMUM---------------------------//
int minimum()
{     contents= new int[count];
      datafile.open(filename,ios::in);       // opens numbers.txt file for reading
// displaying the contents of the file
      for(i=0;i<count;i++)  // keeps reading till the end of file
       {
            datafile>>contents[i]; // read character by character form file  ito words

            cout<<contents[i]<<endl;    // displays characters on the screen

       };
      //find and display min
      for(i=0;i<count;i++)
      {
            if(contents[i]<min)
                  min=contents[i];
       }
       cout<<"min is "<<min<<endl;
  datafile.close(); // close file
      return 0;
}





//-------------OPTION 6 TOTAL---------------------------//
 int total()
 {
        contents= new int[count];
      datafile.open(filename,ios::in);       // opens numbers.txt file for reading
// displaying the contents of the file
      for(i=0;i<count;i++)  // keeps reading till the end of file
       {
            datafile>>contents[i]; // read character by character form file  ito words

            cout<<contents[i]<<endl;    // displays characters on the screen

       };
  // calcualte and display sum
      for(i=0;i<count;i++)
            sum=sum+contents[i];

      cout<<"sum is "<<sum<<"\n";

      datafile.close(); // close file
 return 0;
 }

//-------------OPTION 7 AVERAGE---------------------------//
int average()
{     contents= new int[count];
      datafile.open(filename,ios::in);       // opens numbers.txt file for reading
// displaying the contents of the file
      for(i=0;i<count;i++)  // keeps reading till the end of file
       {
            datafile>>contents[i]; // read character by character form file  ito words

            cout<<contents[i]<<endl;    // displays characters on the screen

       };
      // calclate and display average
      sum=sum2;
      ave=sum2/count;
      cout<<"average is "<<ave<<endl;
      datafile.close(); // close file
return 0;
}
//-------------OPTION 8 SORT---------------------------//
int sort()
{
            char ans;
            contents= new int[count];
            int tp, i, j, total;
            total =  sizeof(contents)/4; // Meaning you can change the size of the array
            for (i=1; i<=total-1; i++)
                  {
                  for (j=i+1; j<=total; j++)
                        {
                          if (contents[i] > contents[j])
                              {
                                     tp = contents[i];
                                     contents[i] = contents[j];
                                     contents[j] = tp;
                              }
                        }
                  }
       for (i=1; i<=total; i++)
                        cout << endl << contents[i];
       cin >> ans;

return 0;
}


 //-------------MAIN PROGRAM---------------------------//

int main()
{

      welcome();
      while(keypress!=67||keypress!=99)
      {
            if (keypress==99||keypress==67)
            {
                  menu();
                  while(keypress!=49||keypress!=50||keypress!=51||keypress!=52||keypress!=53||
                              keypress!=54||keypress!=55||keypress!=56||keypress!=57)
                  {
                        if(keypress==49||keypress==50||keypress==51||keypress==52||keypress==53||
                              keypress==54||keypress==55||keypress==56||keypress==57)
                              {
                                    if(keypress==49)
                                          {            //----- OPTION 1------//
                                                clrscr();
                                                create_file();
                                                cout<<"\n\n\t\t\tPress Any Key To Return to Main Menu";
                                                anykey=getch();
                                           }
                                    if(keypress==50)
                                          {          //----- OPTION 2------//
                                          clrscr();
                                          input_data();
                                          cout<<"\n\n\t\t\tPress Any Key To Return to Main Menu";
                                          anykey=getch();
                                          }
                                    if(keypress==51)
                                          {            //----- OPTION 3------//
                                          clrscr();
                                          view_file();
                                          cout<<"\n\n\t\t\tPress Any Key To Return to Main Menu";
                                          anykey=getch();
                                          }
                                    if(keypress==52)
                                          {            //----- OPTION 4------//
                                          clrscr();
                                          maximum();
                                          cout<<"\n\n\t\t\tPress Any Key To Return to Main Menu";
                                          anykey=getch();
                                          }
                                    if(keypress==53)
                                          {           //----- OPTION 5------//
                                          clrscr();
                                          minimum();
                                          cout<<"\n\n\t\t\tPress Any Key To Return to Main Menu";
                                          anykey=getch();
                                          }
                                    if(keypress==54)
                                          {           //----- OPTION 6------//
                                          clrscr();
                                          total();
                                          cout<<"\n\n\t\t\tPress Any Key To Return to Main Menu";
                                          anykey=getch();
                                          }
                                    if(keypress==55)
                                          {          //----- OPTION 7------//
                                          clrscr();
                                          average();
                                          cout<<"\n\n\t\t\tPress Any Key To Return to Main Menu";
                                          anykey=getch();
                                          }
                                    if(keypress==56)
                                          {         //----- OPTION 8------//
                                          clrscr();
                                          sort();
                                          cout<<"\n\n\t\t\tPress Any Key To Return to Main Menu";
                                          anykey=getch();
                                          }
                                    if(keypress==57)
                                          {        //----- OPTION 9------//
                                          clrscr();
                                          cout<<"\a"<<endl;
                                          cout<<"Thank you for using our program"<<endl;
                                          cout<<"We hope you enjoyed it";

                                          cout<<"\n\n\t\t\tPress Any Key exit the program";
                                          anykey=getch();
                                          break;

                                                             //exit(0);
                                          }

                               }


                        cout<<"\a";
                        clrscr();
                        menu();
                  }// end while of menu validation
            }

            cout<<"\a";
            clrscr();
            welcome();

      }//end while of welcome validation

return 0;
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------
there are 3 problem with my program...
1) the sort code provided by reborn_Assasin---- i ttried but i could'nt integrate his proram into mine.. i tried to look for the problem but iam having difficulty.
2) the exit function dosent work..  in the opt9.. i tried to puta  break; but  it only goes back to the welcome screenn. .
also i tried to put exit(0);  there fore included stdlib.h as header.. but for no apparent reason it gives me  9 errors.. . please could soemone  provide me with a solution for this.
3) the average option---.  initially  my ave was an int .which gave me an int value. .but when i changed it to float .all it gives me is 0..
  please help
  thank you..



20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...