views:

154

answers:

5
+1  Q: 

Sorting in arrays

While sorting an array for ex: A[5]={1,4,5,3,2} the output must be 1,2,3,4,5 in ascending order. in using the concept of bubble sorting my output is 0,1,2,3,4 what would be the problem in my code

  int A[5]={1,5,3,2,4};
     for(int i=0;i<5;i++){
     for(int j=0;j<5;j++){
     if(A[j]>A[j+1])
     {
      int t=A[j];
      A[j]=A[j+1];
      A[j+1]=t;
     }
     }
    }
     for(i=0;i<5;i++)
     cout<<A[i];
+1  A: 

Why not use the STL sort?

#include <algorithm>

std::sort(A, A+5);
Manuel
The "+5" part is slippery thuogh... If `A` is an `array` or `vector`, then one can write `A.size()`, but for C-style array the preferred way probably is to `#define ARRAYSIZE(A) (sizeof(A)/sizeof(A[0]))` and then call `std::sort( A, A + ARRAYSIZE(A) );`
ArunSaha
@ArunSaha: hardly. That breaks silently if `A` is a pointer. If you want to do something like this, use an inline template. Also, I'm not sure why this was downvoted. Seems a sensible answer in the general case. Of course, if the question is a part of a homework assignment or something, the STL version is probably out, but we don't know that.
jalf
@jaif: You are right, if `A` is a pointer then `ARRAYSIZE` does not work. But, that's changing the problem definition too much, in the problem `A` was **not** a pointer :). Also I mentioned `.size()` can be used whenever possible. BTW, it's not me who downvoted.
ArunSaha
A: 

Perhaps you are printing i instead of A[i] in the printing loop, as in

for( int i = 0; i < N; i++ ) {
    cout << i << ",";          // by mistake, printing i instead of A[i]
}
ArunSaha
A: 

Is there a reason you are doing bubble sort, other then trying to learn it? It's one of the slower sorts.

Roman A. Taycher
+3  A: 

You need to limit your inner loop to <4:

int A[5]={1,5,3,2,4};
for(int i=0;i<5;i++){
    for(int j=0;j<4;j++){
        if(A[j]>A[j+1])
        {
           int t=A[j];
           A[j]=A[j+1];
           A[j+1]=t;
        } 
    }
}
for(i=0;i<5;i++)
   cout<<A[i];
JoshD
A: 

Why do you want to use the slowest sorting algorithm known to man?

This page has some excellent sorting algorithms: http://www.eternallyconfuzzled.com/tuts/algorithms/jsw_tut_sorting.aspx

IanC
One reason would be, for example, if only one element is added to the end at a time and the array needs to be re-sorted. Please do not assume qsort or mergesort are the best answer to every possible sorting problem.
MaxVT
Believe it or not, but bubble sort is still being taught. I too had to implement it as a freshman. (I refused and handed in an implementation of insertion sort instead.)
larsmans
@MaxVT I would never think that. Heapsort is good at the scenario you mention.
IanC
@larsmans good for you! I would have done the same thing.
IanC