Why a garbage value is showing at the index (0) after sorting the array in ascending order?

#include <iostream>
using namespace std;

int main(){
int t;
cout << "Enter the array size: ";
cin >> t;
char array[t];
cout << "\nEnter the values:\n";
for(int i=0;i<t;i++){
cin >> array[i];
}

cout << "\n\nThe array before sorting: ";
for(int i=0;i<t;i++){
cout << array[i] << " ";
}

cout << "\n\nThe array after sorting in ascending order: ";
int temp;
for(int i=0;i<t;i++){
for(int j=0;j<t-i;j++){
if(array[j]>array[j+1]){
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
//array[t+1]='\0';
for(int i=0;i<t;i++){
cout << array[i] << " ";
}

cout << "\n\nThe array after sorting in descending order: ";

for(int i=t-1;i>=0;i--){
cout << array[i] << " ";
}


cout << "\n\n\n";
return 0;
}
the problem lies here:
1
2
3
4
5
6
for(int i=0;i<t;i++){
for(int j=0;j<t-i;j++){
if(array[j]>array[j+1]){
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;

you're not sorting by the i'index at all. instead it should be:
1
2
3
4
5
6
7
8
9
for(int i=0;i<t;i++){
for(int j=i+ 1;j<t;j++){
if(array[i]>array[j]){
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
}
Thank you so much
Topic archived. No new replies allowed.