1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
|
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
void arraysort(int* myarray,int* pcount,string order);
void fillarray(int* myarray,int* pcount);
void printarray(int* myarray,int* pcount);
int main(int argc, char** argv) {
int mycount = 0;
int *pcount = &mycount;
string order;
cout << "Enter the array size: " << endl;
cin >> *pcount;
int* myarray = new int[*pcount];
cout << " Now enter some random values the array will sort them : " << endl;
cout << " NO MORE THAN : " << *pcount << " ! " << endl;
fillarray(myarray,pcount);
cout << "Enter the order: ascending/descending: " << endl;
cin >> order;
arraysort(myarray,pcount,order);
printarray(myarray,pcount);
return 0;
}
void fillarray(int* myarray,int* pcount){
int value;
for(int i=0; i< *pcount; i++){
if (cin >> value){
myarray[i] = value;
} else {
cout << " cin failed to get the value !" << endl;
}
}
cin.ignore(100,'\n');
}
void arraysort(int* myarray, int* pcount,string order) {
// BUBBLE SORT
int flag = 1;
int temp;
if (order == "ascending") {
cout << "You picked ascending(small->large)" << endl;
for (int i=1; i <= *(pcount) && flag; i++){
flag = 0;
for (int j=0; j < *(pcount - 1); j++) {
if (myarray[j] > myarray[j + 1]){
//swap the values;
temp = myarray[j];
myarray[j]= myarray[j+1];
myarray[j+1] = temp;
flag = 1; //a swap occured.
}
}
}
} else {
cout << "You picked descending(large->small)" << endl;
for (int i=1;(i <= *pcount) && flag; i++){
flag = 0;
for (int j=0; j < *(pcount - 1);j++) {
if (myarray[j + 1] > myarray[j]){
//swap the values;
int temp = 0;
temp = myarray[j];
myarray[j]= myarray[j+1];
myarray[j+1] = temp;
flag = 1; //a swap occured.
}
}
}
}
cin.ignore(100,'\n');
}
void printarray(int* myarray, int* pcount) {
for(int i = 0; i < *pcount; i++){
cout << myarray[i] << endl;
}
cin.ignore(100,'\n');
}
|