this is my code about bubble sort.
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
using namespace std;
void swap(int &a, int &b) {
int * x = &a;
int * y = &b;
int tmp = * x;
* x = * y;
* y = tmp;
}
int main()
{
// INPUT
int size;
int i=0;
int A[80];
cout << "How many number in your list A ? ";
cin >> size;
for(i=0;i<size;i++) {
cout << " A[" << i << "] = " ;
cin >> A[i];
}
// PRINT LIST
cout << "This is your list number: ";
cout << endl;
for(int i=0; i<=size -1;i++) {
cout << A[i] << " ";
}
// WHILE LOOP , continue if swapped;
bool swapped = true;
int pass=0;
while(swapped == true) {
swapped = false;
// Increase Pass
pass++;
cout << endl << endl << "Pass " << pass << ":";
// Loop size - Pass;
for( i=1; i<=size - pass;i++) {
// check if X > Y
if(A[i-1] > A[i]) {
// true, doing swap
swap(A[i-1], A[i]);
// set swapped to continue next loop
swapped = true;
}
// Print list again after sort;
cout << endl;
for(int i=0; i<=size -1;i++) {
cout << A[i] << " ";
}
}
}
// PRINT after sort;
cout << endl << endl << "Your list after sort: ";
for(int i=0; i<=size -1;i++) {
cout << A[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
On this code,i must enter number of amount (size), and then enter each of A[i].
But I want to improve this code, can i don’t need to enter amount (size), and just cin the the whole A?
Like:
Please enter your list number: 5 1 4 2 8 [enter]
And I get the whole A[];
Just a idea after see first answer. I see, Vector can automatic resize, but if I change into vector, will have any way to enter 1 line ? I just got an idea, I enter a string of number: 1 2 3 4 5, then I enter. do C++ have any function to split by space, and then return back to an array or a vector ? in PHP, I just use $array = explode(” “,$string); >_<
Thanks your help, tried to read many article >_<
What you should use instead of an array, is a vector. Arrays require you to know in advance how many elements will be stored, and if this number is unknown, you have to employ some rather involved memory copying once you need to exceed their predetermined capacity. Vectors do this for you under the hood.
Here’s an example that basically performs what you ask, using a vector:
Now
intListis populated with the integers you have entered, so long as each is separated by a comma.