Hello ;
I need a help in my home work , I have to write the program that prints the number of clock ticks it took the program to sort the data
the main part is already given , I have to wright the functions
this is my program ::
#include<iostream>
using namespace std;
struct Cell{
int data;
Cell* next;
Cell(int d,Cell *n=0){
data=d;
next=n;
}
};
// print all elements in linked-list p
void print(Cell *p){
if(p!=0){
cout<<p->data<<" , ";
print(p->next);
}
}
// deletes all cells in linked-list p
void dispose(Cell *p){
while(p!=0){
Cell *h=p->next;
delete []p;
p=h;
}
}
//returns the number of elements in p that are sorted non-descendingly
int countSorted2 (Cell *p,Cell *h){
if( (h->next != 0) && ( h->next->data > h->next->next->data) )
return 0+countSorted2 (p,h->next);
else
return 1+countSorted2 (p,h->next);
}
int countSorted (Cell *p){
return countSorted2 (p,p);
}
//Inserts data into the sorted list L
void insert2(Cell *& L,Cell *& h ,int data){
if( (h->next!=0) && (h->data > h->next->data) )
insert2 (L,h->next,data);
else
h->next=new Cell(data,0);
}
void insert(Cell* &L, const int data){
insert2(L,L,data);
}
//Builds a linked-list of the N numbers in A , the order of elements is not important
Cell *build2 (int A[],int k,int N){
if( N == 0) return 0;
else
return new Cell (A[k] , build2(A, k+1, N-1));
}
Cell * build(int A[], int N){
return build2 (A,0,N) ;
}
// Splits the list L into two equal sublists p and q , the order of elements is not important
void split(Cell *L, Cell*& p,Cell * &q){
// I need a help here in how to write this function
}
//Merges the lists p and q into a single sorted list , Both p and q are already sorted
Cell *merge(Cell*p , Cell*q){
Cell *h;
if (p->data < q->data){
h->data=p->data;
return merge(p->next,q);
}
else{
h->data=q->data;
return merge(p,q->next);
}
h=h->next;
return h;
}
// this fourth functions are given also
Cell *msort(Cell *L){
if ((L==0) || (L->next == 0)) return L;
else {
Cell *p, *q ;
split(L,p,q) ;
return merge(msort(p),msort(q)) ;
}
}
Cell* merge_sort(int A[], int N) {
return msort(build(A,N)) ;
}
Cell* insertion_sort(int A[], int N){
Cell *L = 0 ;
while (N-- > 0){
insert(L,A[N]) ;
}
return L ;
}
void random(int A[], const int N) {
srand(time(0)) ;
for (int k = 0 ; k < N ; k++) A[k] = rand() % (2*N) - N ;
}
int main(int argc, char** argv){
if (argc != 3){
cout << "Error: Need exactly two arguments: Sort-type & size" << endl ;
return -1 ;
}
char type = *argv[1] ;
int N = atoi(argv[2]) ;
int* data = new int[N] ;
random(data,N) ;
clock_t T0 = clock() ;
Cell* A = (type=='I' || type = 'i') ? insertion_sort(data,N)
: merge_sort(data,N) ;
clock_t T1 = clock() ;
if (countSorted(A) != N)
cout << "logical error in sorting routine!" << endl ;
else
cout << type << " " << N << " " << (T1-T0) << endl ;
if (N < 50) print(A) ;
dispose(A) ;*/
delete [] data ;
cout<<"\n\n";
system("pause");
return 0;
}
thanks;