i trying print iterations of function goes through loop, text after code output should like, first time asking dont know if doing right.
//abdulfattah abutaha's code please use reference only.
#include #include #include #include
using namespace std; void selectionsort(vector<int>& a) { int temp,pos_min; int n=a.size(); (int i=0; < n-1; i++) { pos_min = i; (int j=i+1; j < n; j++) { if (a[j] < a[pos_min]) { pos_min=j; } } if (pos_min != i) { temp = a[i]; a[i] = a[pos_min]; a[pos_min] = temp; } } } int main(){ num=""; nums.clear(); cout<<endl; cout<<"enter next element (enter 'q'to stop):"<<endl; while(num!="q") { cin>>num; if(num == "q") { continue; } cout<<"enter next element (enter 'q'to stop):"<<endl; numbers=stoi(num); nums.push_back(numbers); } selectionsort(nums); cout<<"sequence: "; for(int i=0;i<nums.size();i++) { cout<<nums[i]<<" "; } return 0; }
output:
===selection sort==================================== min -78,swap 90:-78 -8 34 90 34 235 9 -12 653 min -12,swap -8:-78 -12 34 90 34 235 9 -8 653 min -8,swap 34:-78 -12 -8 90 34 235 9 34 653 min 9,swap 90:-78 -12 -8 9 34 235 90 34 653 min 34,swap 34:-78 -12 -8 9 34 235 90 34 653 min 34,swap 235:-78 -12 -8 9 34 34 90 235 653 min 90,swap 90:-78 -12 -8 9 34 34 90 235 653 min 235,swap 235:-78 -12 -8 9 34 34 90 235 653 sequence: -78 -12 -8 9 34 34 90 235 653
do (add 3 lines i've marked.) note haven't tried this.
void selectionsort(vector<int>& a) { cout << "===selection sort====================================" << endl; // <-- int temp,pos_min; int n=a.size(); (int i=0; < n-1; i++) { pos_min = i; (int j=i+1; j < n; j++) { if (a[j] < a[pos_min]) { pos_min=j; } } cout << "min " << a[pos_min] << ", swap " << a[i] << ":"; // <-- if (pos_min != i) { temp = a[i]; a[i] = a[pos_min]; a[pos_min] = temp; } (int k = 0; k < n; ++k) cout << " " << a[k]; cout << endl; // <-- } }
Comments
Post a Comment