Basic Concept:
Name is an Array of Characters and to sort an array of names and to store them in a List, we require a Double Dimensional Array of Characters . Where first index used to represents List of Names and the second index used to store List of Characters in Name.
#include<iostream.h>
#include<string.h>
#define SIZE 30
void swap(char one[SIZE],char two[SIZE]) //to swap two name (STRINGS)
{
char tmp[SIZE];
strcpy(tmp,one);
strcpy(one,two);
strcpy(two,tmp);
}
void sort(char array[][SIZE],int num) //Function to Sort the ARRAY of Names
//In Called function first index of array must be empty
{
for(int i=0;i<num;++i)
{
for(int j=i+1;j<num;++j)
{
if(strcmp(array[i],array[j])>0) //if the name is greater than it's subsequent call swap
{
swap(array[i],array[j]);
}
}
}
}
int main()
{
char names[SIZE][SIZE];
int n;
cout<<"Please enter number of names :"<<endl;
cin>>n; //Reading number of names
cout<<"Please enter the names separated By 'White Space' or 'Newline ( ENTER )' : "<<endl;
for(int i=0;i<n;++i)
{
cin>>names[i]; //Reading the names into array
}
cout<<"Given names before sorting are :"<<endl;
for(int i=0;i<n;++i)
{
cout<<names[i]<<endl; //Verifying array list and order of names
}
sort(names,n); //calling Sort Function
cout<<"Given names in ascending order are :"<<endl;
for(int i=0;i<n;++i) //Displaying Sorted array of names
{
cout<<names[i]<<endl;
}
return 0;
}
Name is an Array of Characters and to sort an array of names and to store them in a List, we require a Double Dimensional Array of Characters . Where first index used to represents List of Names and the second index used to store List of Characters in Name.
#include<iostream.h>
#include<string.h>
#define SIZE 30
void swap(char one[SIZE],char two[SIZE]) //to swap two name (STRINGS)
{
char tmp[SIZE];
strcpy(tmp,one);
strcpy(one,two);
strcpy(two,tmp);
}
void sort(char array[][SIZE],int num) //Function to Sort the ARRAY of Names
//In Called function first index of array must be empty
{
for(int i=0;i<num;++i)
{
for(int j=i+1;j<num;++j)
{
if(strcmp(array[i],array[j])>0) //if the name is greater than it's subsequent call swap
{
swap(array[i],array[j]);
}
}
}
}
int main()
{
char names[SIZE][SIZE];
int n;
cout<<"Please enter number of names :"<<endl;
cin>>n; //Reading number of names
cout<<"Please enter the names separated By 'White Space' or 'Newline ( ENTER )' : "<<endl;
for(int i=0;i<n;++i)
{
cin>>names[i]; //Reading the names into array
}
cout<<"Given names before sorting are :"<<endl;
for(int i=0;i<n;++i)
{
cout<<names[i]<<endl; //Verifying array list and order of names
}
sort(names,n); //calling Sort Function
cout<<"Given names in ascending order are :"<<endl;
for(int i=0;i<n;++i) //Displaying Sorted array of names
{
cout<<names[i]<<endl;
}
return 0;
}
No comments:
Post a Comment