C++ Bubble Array Assignment - Adding markers to show change -
i given assignment work through in university , 1 part of assignment add stars(*) elements moved in array using bubble sort. i've tried few different things try work nothing ends working. here what's asked of me:
"5. create array of bools (one each element in array), if pair of elements changed round in cycle, bools change true, , elements displayed surrounded stars (
*) show change has occurred. reset array of bools false, ready next cycle. remember need test value of boolean in order decide whether output asterisks or not"
here code:
int main() { double numbers[nmax] = {31.2, 29.7, 53.5, 69.0, 23.7, 71.8, 49.3, 52.9, 51.3, 57.1}; bool change[nmax] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // note top counter, i, counts down int counter = 0; (int i=nmax-1; i>0; i--) { //and counter, j, goes far current value // means doesn't go on elements have 'bubbled up' end of array (int j=0; j<i; j++) { double temp; // compare 2 values - increment counter here counter++; if (numbers[j]>numbers[j+1]) { temp = numbers[j]; numbers[j]= numbers[j+1]; numbers[j+1]= temp; cout << "array: " << endl; change[j] = true; change[j + 1] = true; (int = 0; < 10; i++) { cout << numbers[i] << ", "; } } } } // display sorted array: cout << endl; cout<<"array contents sorted, implementation 1 "<<endl; (int i=0; i<nmax; i++) { cout<<numbers[i]<<endl; } //display values of counter after whole sort return 0; } i'm new stackoverflow, apologies if question irritatingly formatted.
i don't understand why array of bools required if still remember j , j+1 exchanged when output numbers. write simply:
for (int n = 0; n < nmax; ++n) { if (n == j + 1 || n == j) cout << '*' << numbers[n] << "*, "; else cout << numbers[n] << ", "; } however if there such requirement follow , try achieve same effect checking contents of bool array of yours. remember reset false required.
Comments
Post a Comment