You got few problems in your code the most problematic are:
wrong swap (last line should be reversed)
you are looping the whole thing N-1
times
that is needlessly too much loop only until array is sorted instead. So until no swap occurs in the inner loop.
I code ascending Bubble sort like this (in C++):
void sort_asc(int *a,int n)
{
int i,e;
for (e=1;e;n--) // loop until no swap occurs
for (e=0,i=1;ia[i]) // if swap needed
{
e=a[i-1]; // swap
a[i-1]=a[i];
a[i]=e;
e=1; // allow to process array again
}
}
usage:
int a[]={ 9,8,7,6,5,4,3,2,1,0 }; // worse case scenario
sort_asc(a,sizeof(a)/sizeof(a[0]));
Descending order is just matter of changing condition to:
if (a[i-1]
btw here some measurements of sorting 32bit int a[1024]
arrays looped 100 times:
Time Space
[ 1.428 ms] Worse case O(n)
[ 312.744 ms] Bubble asc O(n^2) O(1 ) OK
[ 306.084 ms] Bubble dsc O(n^2) O(1 ) OK
[ 9.883 ms] Quick asc O(n.log(n)) O(log(n)) OK
[ 10.620 ms] Quick dsc O(n.log(n)) O(log(n)) OK
[ 1.816 ms] Random O(n)
[ 374.343 ms] Bubble asc O(n^2) O(1 ) OK
[ 361.219 ms] Bubble dsc O(n^2) O(1 ) OK
[ 14.402 ms] Quick asc O(n.log(n)) O(log(n)) OK
[ 14.519 ms] Quick dsc O(n.log(n)) O(log(n)) OK
asc and desc sorts have the same speed the slight measured difference is only due to CACHE as they both use the same memory space so which one is called in test first will be slower and second one benefits from the fact the memory is mapped in CACHE already (if not too large of coarse). btw this code can be further optimized by a bit...