I'm trying to create a sorting algorithm, it contains a nested loop which compares each element of the array to all other elements in the array, and if an element is greater in value than any of its succeeding elements, they switch places with each other. But for some reason my program won't output anything and exits with code 0, i.e. success.
Following is my code:
#include <iostream>
using namespace std;
void sortAlgo(int *a, int n){
int tmp;
for (int i=0; i<=n-1; i++){
for(int j=i+1; j<=n; j++){ //O(n^2)
if(a[i]>a[j]){
//LHS variable assumes RHS quantity
tmp=a[i]; //a[i] value stored in temp variable
a[i]=a[j]; //shifts a[j] value to a[i]
a[j]=tmp; //a[j] takes value of a[i]
}
}
}
for(int x=0; x<=n; x++){
cout<<a[x]<<" ";
}
}
int main(){
int arr[10]={1,2,3,5,23,12,4};
sortAlgo(arr, 7);
}
I am using VS Code.
<=in a loop condition you are probably going out of bounds. Likefor(int x; x<=n; x++)andfor(int j=i+1; j<=n; j++).for (int i=0; i<=n-1; i++)could be rewritten asfor (int i=0; i < n; i++).for(int x; x<=n; x++), what's the initial value ofx? It's undefined, so it's random garbage at runtime (likely not zero), so the code doesn't output anything.