The problem with your code is that you try to bubble stuff down, but loop upward. If you want to bubble stuff down, you need to loop downward so an element that needs to go down goes down as far as it needs to. Otherwise, with every iteration of i
you only know that an element may be bubbled down one space.
Similarly, if you bubble things upwards, you also need to loop upwards.
If you want to see what happens, here's your code with some output statements so you can follow what's going on:
#include <iostream>
using namespace std;
template <class T>
void sort(T a[], int size){
for(int i=0; i<size; i++){
cout << "i: " << i << endl;
for(int j=0; j<i-1; j++){
if(a[j+1]>a[j]){
cout << "\t Yes at j = " << j << endl;
T temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
for(int k = 0; k < size; k++) {
cout << "\t a[" << k << "]: " << a[k] << endl;
}
cout << endl;
}
}
cout << "\n" << endl;
}
}
int main(){
int a[] = {1,2,6,3,4,9,8,10};
cout << "initially:" << endl;
for(int k = 0; k < 8; k++) {
cout << "a[" << k << "]: " << a[k] << endl;
}
cout << "\n" << endl;
sort<int>(a,8);
cout << "\n sorted:" << endl;
for(int i = 0; i<8; i++){
cout << a[i] << endl;
}
return 0;
}
If you run this, you can see that for entries with higher index, there aren't enough iterations left to bubble them down all the way to where they need to go.
Also, here's code with your bubbling-down fixed (i.e. sorting in reverse order):
#include <iostream>
using namespace std;
template <class T>
void sort(T a[], int size){
for(int i=0; i<size; i++){
cout << "i: " << i << endl;
for(int j=size - 1; j>i; j--){
if(a[j-1]<a[j]){
cout << "\t Yes at j = " << j << endl;
T temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
}
}
}
int main(){
int a[] = {1,2,3,4,5,6,8,10};
sort<int>(a,8);
cout << "\n sorted:" << endl;
for(int i = 0; i<8; i++){
cout << a[i] << endl;
}
return 0;
}