12 May 2009

bubble sorting algorithm

// this program is to sort words from a file ascending or descending by bubble sorting algorithm
//0
#include <iostream>
#include <string>
#include <fstream>
//1
using namespace std;
//2
int main ()
{
// declare   
  string a[21000];  // define huge array
  string s = "";
  int k, z = 0;
// import all the words in an array 
  ifstream word;
  word.open("words.txt");
  while (! word.eof()) 
      {
            word >> a[z]; // insert new word; do z++
            z++;
      };
// sort the array using bubble sorting algorithm
    for (int i = 0; i < z; i++)
        {
            for ( k = 1; k < (z - i); k++) // each word we do n-itsPosition comparisons
            {
                if (a[i+k] < a[i])    // for ascending use <; for descending use >
                 {
                    s = a[i];
                    a[i] = a[i+k];
                    a[i+k] = s;
                  }
            }
        }
             
// print out the sorted words
    for (int j = 0; j < z; j++)     // z is number of lines in file
        cout << a[j] << endl; 
// pause
    system("PAUSE");   
    return 0;
}