0

C++, Bubble sort, how to change the code to see every step of sort in the output?

Task is: Input In the first line of input, one integer n(1<=n<=1000) is given. The secon line contains n natural numbers - sequence of numbers to be sorted Output You should print k lines, where k is the required number ofiterations through the array to sort the string. The last line ahould be a sorted string. In case the string on the input is sorted, nothing needs to be printed. Example: Input 5 1 2 3 5 4 Output 1 2 3 4 5 Input 5 5 9 3 1 2 Output 5 3 1 2 9 3 1 2 5 9 1 2 3 5 9 Input 5 10 100 1000 10000 100000 Output And code so far: #include <iostream> #include <string> int bubblesort() { int max; std::cin>>max; int *numarray=new int[max]; for(int i = 0; i <max; i++) { std::cin>>numarray[i]; } std::cout<<"\n"; for(int i=1; i<max; i++) { for(int j=0; j<max - i; j++) { if(numarray[j]>numarray[j+1]) { int temp=numarray[j]; numarray[j]=numarray[j+1]; numarray[j+1]=temp; } } for(int k=0; k<max; k++) std::cout<<numarray[k]<<" "; std::cout<<"\n"; } for(int i=0; i<max; i++) { Continued below...........

3rd Feb 2021, 3:08 PM
Martyna Tomaszewska
Martyna Tomaszewska - avatar
4 Antworten
0
std::cout<<numarray[i]; std::cout<<" "; } delete [] numarray; return 0; } int main() { bubblesort(); return 0; }
3rd Feb 2021, 3:11 PM
Martyna Tomaszewska
Martyna Tomaszewska - avatar
0
//worked for me in selection sort tho include <iostream> using namespace std; int main() { int array_size = 5; int arr[array_size]; // arr[5] // create elements for array for(int k = 0; k < array_size; k++){ arr[k] = rand()%10; // random arr elements } // output the elements cout <<"unsorted array: " << endl; for(int i = 0; i < array_size; i++){ cout << arr[i] << " "; } cout << endl << endl; // now sort starts int low; int temp; for(int i = 0; i < array_size -1; i++){ low = i; for(int j = i + 1; j< array_size; j++){ if(arr[j] < arr[low]){ low = j; } } temp = arr[low]; arr[low] = arr[i]; arr[i] = temp; for(int k = 0; k < array_size; k++){ cout << arr[k] << " "; } cout << endl; } cout << endl; // output sorted array cout << "sorted array: "
3rd Feb 2021, 7:06 PM
Maher Al Dayekh
Maher Al Dayekh - avatar
0
// output sorted array cout << "sorted array: "<<endl; for(int k = 0; k < array_size; k++){ cout << arr[k] << " "; } return 0; }
3rd Feb 2021, 7:07 PM
Maher Al Dayekh
Maher Al Dayekh - avatar
0
It is working but in my program i need to 'cin' random number of array elements and random elements. This program contains already all this informations.
4th Feb 2021, 3:40 PM
Martyna Tomaszewska
Martyna Tomaszewska - avatar