Sorting source code

#include<iostream>
#include<fstream>
#include<string>
#include<conio.h>
#include<windows.h>
#include<time.h>
#include<ctime>
using namespace std;
class movienames{
private:
char *name;
char max;
public:
movienames operator=(movienames * a){
movienames  temp;
strcpy(name,a->name);
return temp;
}
char * getname(){
return name;
}
void setname(char *str,int i){
name=new char[i];
max=i;
strcpy(name,str);
}
void print(){
for(int i=0;i<max;i++){
cout<<name[i];}
cout<<endl;
}
/*~movienames(){
cout<<"\nDestructor called";
delete [] name;
}*/
};
void bubblesort(movienames * a,int n){
int flag=1;
int steps=0;
for(int i = 1; (i <= n) && flag; i++)
     {
 steps++;
          flag = 0;
 steps++;
          for (int j=0; j < (n -1); j++){
 steps++;
 if (strcmp(a[j+1].getname(),a[j].getname())<0){
swap(a[j+1],a[j]);
                flag = 1;
steps+=3;
 }}}
cout<<n<<"\t"<<steps<<endl;
}
void insertionsort( movienames * a,int n)
{
int steps=0;
movienames key;
     int i, j;
     for(j = 1; j < n; j++)    // Start with 1 (not 0)
    {
steps++;
           key=a[j];
  steps++;
  for(i = j - 1;(i >= 0) && (strcmp(a[i].getname(),key.getname())>0); i--)   // Smaller values move up
         
  {
steps++;
                 a[i+1] = a[i];
steps++;
          }
         a[i+1] = key;  
steps++;
//Put key into its proper location
     }
cout<<n<<"\t"<<steps;
     return;
}
void selectionsort( movienames * a,int n)
{
      int i, j, first;
 int steps=0;
 movienames temp;
     for (int i = 0; i < (n - 1); i++)
    {
steps++;
        int minIndex = i;
steps++;
        // Find the index of the minimum element
        for (int j = i + 1; j < n; j++)
        {
steps++;
if (strcmp(a[j].getname(),a[minIndex].getname())<0)
            {
steps++;
                minIndex = j;
            }
        }

        // Swap if i-th element not already smallest
        if (minIndex > i)
        {
steps++;
            swap(a[i], a[minIndex]);
        }
    }
 cout<<n<<"\t"<<steps<<endl;
     return;
}
int main(){
time_t start,end;
int count=0;
string stri;
fstream file("movies.txt",ios::in);
while(!file.eof()){
getline(file,stri);
count++;
}
movienames * m=new movienames[10815];
file.close();
file.open("movies.txt",ios::in);
for(int i=0;i<count;i++){
getline(file,stri);
char * temp=new char[stri.length()+1];
for(int i=0;i<stri.length();i++){
temp[i]=stri[i];
}
temp[stri.length()]='\0';

m[i].setname(temp,stri.length());
}


time(&start);
selectionsort(m,10);
time(&end);
//for(int i=0;i<10000;i++){
// m[i].print();
//}
cout<<"Sorting done in "<<end-start<<" Seconds\n";
return 0;
}

Comments

Popular Posts