0

That is my function:

int main() { double data[100]; int num; cout<<"num= "; cin>>num; for(int i = 1; i <= num; i++) { cout<<i<<" element = "; cin>>data[i]; } Sort(data, num); for (int i = 1; i <= num; i++) { cout<<data[i]<<endl; } return 0; } void Sort(double data[], int n) { int i,j,k; double min; for(i = 0; i < n-1; i++) { k = i; min = data[k]; for(j = i+1; j < n; j++) if(data[j] < min) { k = j; min = data[k]; } data[k] = data[i]; data[i] = min; } } 

if I write for exp. three elements: 8,9,1 again cout 8,9,1?

1
  • 2
    Did you steph through your code to see what was happening? Commented Sep 27, 2012 at 1:37

3 Answers 3

1
for(int i = 1; i <= num; i++) { // WRONG 

I think you mean:

for(int i = 0; i < num; i++) { // RIGHT 

Arrays in C are 0-indexed remember.

Sign up to request clarification or add additional context in comments.

Comments

1

Your sorting function is fine. The only problem is that you enter elements at positions 1 through n, inclusive, while you should use 0 through n-1, inclusive, in both loops of the main() function.

If you need to print numbers 1 through n, use

cout<<(i+1)<<" element = "; 

Comments

1

You should get used of the 0 index begin in the for loop for(int i = 0; i < N; ++i)

so fixing these two index errors will make your code run properly.

the reason is:

if you write data to data[] using 1 as the begining, your data array's first item will be a random number:

if you insert 3 elements, the array will be like this:

data[0] = ??? // maybe a very very big number data[1] = 8 data[2] = 9 data[3] = 1 

and in your Sort function, your index begins at 0 and ends before num, that means your code would only sort data[0], data[1], data[2].

if you use: num = 3, 3 2 1 as your input data for the origin code you could see that 3 and 2 is sorted

I guess your Sort code is googled from somewhere, please try to understand it.

Good online algorithm course: https://www.coursera.org/course/algs4partI

a very good algorithm online book: http://algs4.cs.princeton.edu/home/

btw, for(j = i+1; j < n; j++) in the Sort function would be better if it has { } braces.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.