#include <iostream>
usingnamespace std;
/*
This program will create an AList object and will then make some method calls.
*/
constint MLS = 50;
typedefint element;
const element SENTINEL = -1;
class AList {
private:
element items [MLS];
int size;
void Swap(int pos1,int pos2);
int Read_element();
public:
void Read();
void Print();
void BubbleSort();
void InsertionSort();
void SelectionSort();
};
int main (){
int a;
AList B;
B.Read();
B.Print();
B.BubbleSort();
B.Print();
B.Read();
B.Print();
B.InsertionSort();
B.Print();
B.Read();
B.Print();
B.SelectionSort();
B.Print();
}
element Read_element() {
element userval;
cin>>userval;
while (!cin.good());
cout<<"invalid choice please enter a whole number";
cin.clear();
cin.ignore(80, '\n');
cin>>userval;
return userval;
}
void AList::Read() {
//PRE: None
//POST: the N.O. Alist is valid
//using elements provided by the user
element userval;
cout<<"Enter elements,";
while ((userval!=SENTINEL)&&(size<MLS)) {
items[size] = userval;
size ++;
}
}
void AList::Print() {
for (int i=0;i<size;i++)
cout<<items[i]<<endl;
}
void AList::BubbleSort(){
//PRE: the N.O. List is void
//Post: the N.O. Alist is unchanged except
//its elements are now in ascending order
for (int i=0; size=-1; i++) {
for (int j=0; j<size-1-i; j++)
if (items[j]>items[j+1])
Swap (j,j+1);
else
;
}
}
void AList::Swap(int pos1,int pos2) {
element temp;
temp = items[pos2];
items[pos2] = items[pos1];
items[pos1] = temp;
}
void AList::InsertionSort() {
//Pre: the N.O. Alist is valid
//Post: the N.O. Alist is unchanged, except that
//its elements are now in ascending order
int j;
bool done;
for (int i = 1; i<size; i++) {
j=i;
done=false;
while ((j>=1)&&(!done))
if (items[j] < items[j-1]){
Swap(j, j-1);
j-=1;
}
else
done = true;
}
}
void AList::SelectionSort() {
int maxpos;
for (int i = size - 1; i > 0; i--) {
maxpos = 0;
for (int j = 1; j <= i; j++)
if (items[j] > items[maxpos])
maxpos = j;
else
;
Swap(maxpos, i);
}
}